我想有下面的代码在更紧凑的方式(一行或两行)写我的功能更紧凑
foo.txt的:
a:1
b:2
c:3
代码:
>>> r = {}
>>> for i in open('foo.txt','r').readlines():
... k,v = i.split(':')
... r[k]=v.strip()
我想有下面的代码在更紧凑的方式(一行或两行)写我的功能更紧凑
a:1
b:2
c:3
>>> r = {}
>>> for i in open('foo.txt','r').readlines():
... k,v = i.split(':')
... r[k]=v.strip()
如何:
In [43]: with open("foo.txt") as fd:
my_dict=dict(x.strip().split(":") for x in fd)
....:
In [44]: my_dict
Out[44]: {'a': '1', 'b': '2', 'c': '3'}
另一种方法:
In [46]: with open("foo.txt") as fd:
my_dict={k:v for k,v in (x.strip().split(':') for x in fd)}
....:
In [47]: my_dict
Out[47]: {'a': '1', 'b': '2', 'c': '3'}
另一种选择是使用csv
模块:
import csv
with open('input.txt', 'r') as csvfile:
r = {row[0]: row[1] for row in csv.reader(csvfile, delimiter=":")}
我喜欢它!很好的方式来做到这一点 – Vor 2013-05-04 17:20:30
这真的非常紧凑已经和收益没有被写在少线。
但如果你真的有必要,在这里它是在同一行:
r = dict(i.strip().split(':') for i in open('foo.txt','r').readlines())
我不建议这样做,你的现有代码就好了。
这不会从左侧剥离值...例如,这行:'a:3' – stalk 2013-05-04 17:20:58
非常有用,谢谢! – Vor 2013-05-04 17:21:22