2013-05-04 43 views
-1

我想有下面的代码在更紧凑的方式(一行或两行)写我的功能更紧凑

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() 

回答

3

如何:

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'} 
+0

这不会从左侧剥离值...例如,这行:'a:3' – stalk 2013-05-04 17:20:58

+0

非常有用,谢谢! – Vor 2013-05-04 17:21:22

1

好,如果你只关心线数这将做

[r[i.split(':')[0]]=i.split(':')[1] for i in open('foo.txt','r').readlines()] 
+0

awsemoe!谢谢 – Vor 2013-05-04 17:19:28

+0

,但这是丑陋的代码大声笑 – marcadian 2013-05-04 17:20:13

+0

它))但这就是我正在寻找 – Vor 2013-05-04 17:22:27

1

另一种选择是使用csv模块:

import csv 

with open('input.txt', 'r') as csvfile: 
    r = {row[0]: row[1] for row in csv.reader(csvfile, delimiter=":")} 
+1

我喜欢它!很好的方式来做到这一点 – Vor 2013-05-04 17:20:30

0

这真的非常紧凑已经和收益没有被写在少线。

但如果你真的有必要,在这里它是在同一行:

r = dict(i.strip().split(':') for i in open('foo.txt','r').readlines()) 

我不建议这样做,你的现有代码就好了。