2013-05-04 67 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()) 

我不建議這樣做,你的現有代碼就好了。