我是python的新手,对列表中的商店列有疑问,并将其转换为字典,如下所示:
我在下面显示的两列中有一个数据,包含节点(N)和边(E),我想首先列出这两列,然后将这两列的字典作为
{1:[9,2,10],2:[10,111,9],3:[166,175,7],4:[118,155,185]}
。
我该怎么做?感谢。
N E
1 9
1 2
1 10
2 10
2 111
2 9
3 166
3 175
3 7
4 118
4 155
4 185
答案 0 :(得分:6)
defaultdict是dict
的子类,在这里很有用:
import collections
result=collections.defaultdict(list)
for n,e in zip(N,E):
result[n].append(e)
答案 1 :(得分:2)
yourDict={}
for line in file('r.txt', 'r'):
k , v = line.split()
if k in yourDict.keys():
yourDict[k].append(v)
else:
yourDict[k] = [v]
print yourDict
输出: (您可以随时删除N:E)
{'1': ['9', '2', '10'], '3': ['166', '175', '7'], '2': ['10', '111', '9'], '4': ['118', '155', '185'], 'N': ['E']}
答案 2 :(得分:2)
以下没有for循环边缘。该迭代由Python使用内置方法在内部处理,对于大型图形来说可能更快:
import itertools
import operator
N = [ 1, 1, 1, 2, 2]
E = [ 2, 3, 5, 4, 5]
iter_g = itertools.groupby(zip(N,E), operator.itemgetter(0))
dict_g = dict( (v, map(operator.itemgetter(1), n)) for v,n in iter_g )
此外,如果您只需要一次数据,则可以使用iter_g而不构建字典。
答案 3 :(得分:1)
比unutbu的版本慢一点,但更短:)
result = { }
for n, e in ( line.split( ) for line in open( 'r.txt' ) ):
result[ n ] = result.setdefault( n, [ ] ) + [ e ]
答案 4 :(得分:1)
这完全符合您的要求:
import collections
N = []
E = []
with open('edgelist.txt', 'r') as inputfile:
inputfile.readline() # skip header line
for line in inputfile:
n,e = map(int,line.split())
N.append(n)
E.append(e)
dct = collections.defaultdict(list)
for n,e in zip(N,E):
dct[n].append(e)
dct = dict(dct)
print dct
# {1: [9, 2, 10], 2: [10, 111, 9], 3: [166, 175, 7], 4: [118, 155, 185]}
答案 5 :(得分:0)
这是简短的回答:
l1 = [1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4]
l2 = [9, 2, 10, 10, 111, 9, 166, 175, 7, 118, 155,185]
d = dict((i,[j for j,k in zip(l2,l1) if k == i]) for i in frozenset(l1))