题目在哪看到的不记得了,就记下了个解决方法:
#!/usr/bin/env python #coding=utf-8 #方法一 def read_line(line): sample = {} n = len(line) for i in xrange(n): if line[i]!='0': sample[i] = int(line[i]) return sample #方法二 def xread_line(line): return((idx,int(val)) for idx, val in enumerate(line) if val != '0') print read_line('0001110101') print list(xread_line('0001110101'))
效果如下:
{9: 1, 3: 1, 4: 1, 5: 1, 7: 1}
[(3, 1), (4, 1), (5, 1), (7, 1), (9, 1)]