-1

I would like to have the code below in more compact way ( one or two lines )

foo.txt:

a:1
b:2
c:3

code:

>>> r = {}
>>> for i in open('foo.txt','r').readlines():
...     k,v = i.split(':')
...     r[k]=v.strip()
4

4 回答 4

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'}
于 2013-05-04T17:18:55.600 回答
1

好吧,如果您只关心行数,那就可以了

[r[i.split(':')[0]]=i.split(':')[1] for i in open('foo.txt','r').readlines()]
于 2013-05-04T17:18:46.760 回答
1

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

import csv

with open('input.txt', 'r') as csvfile:
    r = {row[0]: row[1] for row in csv.reader(csvfile, delimiter=":")}
于 2013-05-04T17:19:33.590 回答
0

这已经非常紧凑了,并且没有从用更少的行数中获得任何好处。

但是,如果您真的必须这样做,那么它就在一行中:

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

我不推荐它,您现有的代码就可以了。

于 2013-05-04T17:27:46.627 回答