簡體   English   中英

Python:將數據存儲到兩個列表中,然后轉換為字典

[英]Python: Store the data into two lists and then convert to a dictionary

我是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

defaultdictdict的子類,在這里很有用:

import collections
result=collections.defaultdict(list)
for n,e in zip(N,E):
    result[n].append(e)
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']}

以下內容沒有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而不構造字典。

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

result = { }
for n, e in ( line.split( ) for line in open( 'r.txt' ) ):
    result[ n ] = result.setdefault( n, [ ] ) + [ e ]

這完全符合您的要求:

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

這是簡短的回答:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM