Python putting non uniform lines into a dictionary
输入文件如下:
1 2 3 4 5 | A 3.00 B 4.00 C 5.00 D 6.00 E 3.20 F 6.00 G 8.22 H 9.00 I 9.23 J 89.2 K 32.344 |
我希望这些字符是字典里的关键而浮点数则是值。
这是到目前为止我的非工作失败。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | def main(): #Input File reader = open('candidate.txt', 'r' my_dictionary = {} i=0 for line in reader.readlines(): variable = line.split(' ')[i] value = line.split(' ')[i+1] my_dictionary[variable]= value i+=2 print my_dictionary if __name__ == '__main__': main() |
号
1 2 3 4 5 6 7 8 9 10 | s='''A 3.00 B 4.00 C 5.00 D 6.00 E 3.20 F 6.00 G 8.22 H 9.00 I 9.23 J 89.2 K 32.344 ''' s=s.split() d=dict(zip(s[::2], s[1::2])) print d |
上下文:
1 2 3 4 5 | my_dict = dict() for line in reader.readlines(): pairs = line.split() for key, value in zip(pairs[::2],pairs[1::2]): my_dict[key] = value # strip() not needed |
号
1 2 | with open('candidate.txt', 'r') as reader: print dict(zip(*[iter(reader.read().split())]*2)) |
下面是一个使用迭代器的解决方案,它对流进行操作(因此不取决于首先读取整个输入):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | from itertools import izip def group(iterable, n): """Yield iterable's items n at a time""" args = [iter(iterable)]*n return izip(*args) def dictize(stream): r = {} for line in stream: for k,v in group(line.split(), 2): r[k] = v return r from StringIO import StringIO testinput ="""A 3.00 B 4.00 C 5.00 D 6.00 E 3.20 F 6.00 G 8.22 H 9.00 I 9.23 J 89.2 K 32.344""" teststream = StringIO(testinput) print dictize(teststream) |
如果可以使用字典理解,则可以用一行代码替换
1 | print {k:v for line in teststream for k,v in group(line.split(),2)} |
。