Python:将数据存储到两个列表中,然后转换为字典

Python:将数据存储到两个列表中,然后转换为字典,python,list,dictionary,Python,List,Dictionary,我是python新手,对于在列表中存储列并将其转换为字典,我有一个问题,如下所示: 我有一个如下所示的两列数据,其中有节点(N)和边(E),我想首先列出这两列,然后将这两列作为字典 {1:[9,2,10],2:[10111,9],3:[166175,7],4:[118155185]} 我该怎么做?谢谢 N E 1 9 1 2 1 10 2 10 2 111 2 9 3

我是python新手,对于在列表中存储列并将其转换为字典,我有一个问题,如下所示:

我有一个如下所示的两列数据,其中有节点(N)和边(E),我想首先列出这两列,然后将这两列作为字典

{1:[9,2,10],2:[10111,9],3:[166175,7],4:[118155185]}

我该怎么做?谢谢

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
A是dict的一个子类,在这里很有用:

import collections
result=collections.defaultdict(list)
for n,e in zip(N,E):
    result[n].append(e)
输出: (您始终可以在最后一个选项中删除N:E)


比unutbu的版本慢一点,但更短:)


这正是您想要的:

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]}

以下内容在边上没有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而不构建字典。

以下是简短的答案:

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

上面显示的数据位于文本文件中,而不是列表中。你能告诉我你的变量列表是什么吗?谢谢。@Harpreet:如果您已经定义了列表
N
E
,那么我发布的代码可以直接使用
collections.defaultdict(list)
创建一个类似dict的对象,这样当dict中没有
key
时,
result[key]
会自动设置为等于一个空的
列表。@Harpreet:文档()中给出的示例非常接近您的情况。如果你学习这个例子,并且知道
zip
是如何工作的(),那么你就会理解我的代码。@Harpreet:
list
是一种内置类型<代码>[1,2,8]
是一个
列表
。调用时,
list()
返回一个空列表:
[]
。每当使用不存在的键访问名为
result
defaultdict
时,都会调用
list
来提供默认值(空列表),并将其添加到字典中。@Steven Rumbalski:感谢您添加的解释。@Harpreet:已添加,如何用简短而简单的答案来处理狙击的文件问题。但我无法抗拒。
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]}
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 )
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))