[英]Creating a dictionary from a list
從此元組列表中:
[('IND', 'MIA', '05/30'), ('ND', '07/30'), ('UNA', 'ONA', '100'), \
('LAA', 'SUN', '05/30'), ('AA', 'SN', '07/29'), ('UAA', 'AAN')]
我想創建一個字典,其鍵將是每三個元組的 [0]
和[1]
值。 因此,創建的dict的第一把鑰匙應該是'IND, MIA'
,第二把鑰匙'LAA, SUN'
最終結果應為:
{'IND, MIA': [('IND', 'MIA', '05/30'), ('ND', '07/30'), ('UNA', 'ONA', '100')],\
'LAA, SUN': [('LAA', 'SUN', '05/30'), ('AA', 'SN', '07/29'), ('UAA', 'AAN')]}
如果這有任何關系,則一旦所討論的值成為鍵,就可以將它們從元組中刪除,因為從那以后我就不再需要它們了。 任何建議,不勝感激!
inp = [('IND', 'MIA', '05/30'), ('ND', '07/30'), ('UNA', 'ONA', '100'), \
('LAA', 'SUN', '05/30'), ('AA', 'SN', '07/29'), ('UAA', 'AAN')]
result = {}
for i in range(0, len(inp), 3):
item = inp[i]
result[item[0]+","+item[1]] = inp[i:i+3]
print (result)
Dict理解解決方案是可能的,但有些混亂。
要從數組中刪除鍵,請將第二條循環線( result[item[0]+ ...
)替換為
result[item[0]+","+item[1]] = [item[2:]]+inp[i+1:i+3]
Dict理解解決方案(比我最初想象的要混亂的多:)
rslt = {
inp[i][0]+", "+inp[i][1]: inp[i:i+3]
for i in range(0, len(inp), 3)
}
並在答案中添加更多猶太潔食,這是一些有用的鏈接:): defaultdict , dict comprehensions
from itertools import izip_longest
def grouper(iterable, n, fillvalue=None):
"Collect data into fixed-length chunks or blocks"
# grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx
args = [iter(iterable)] * n
return izip_longest(fillvalue=fillvalue, *args)
{', '.join(g[0][:2]): g for g in grouper(inputlist, 3)}
應該這樣做。
grouper()
方法一次為我們提供了3個元組的組。
也從字典值中刪除鍵值:
{', '.join(g[0][:2]): (g[0][2:],) + g[1:] for g in grouper(inputlist, 3)}
您輸入的演示:
>>> from pprint import pprint
>>> pprint({', '.join(g[0][:2]): g for g in grouper(inputlist, 3)})
{'IND, MIA': (('IND', 'MIA', '05/30'), ('ND', '07/30'), ('UNA', 'ONA', '100')),
'LAA, SUN': (('LAA', 'SUN', '05/30'), ('AA', 'SN', '07/29'), ('UAA', 'AAN'))}
>>> pprint({', '.join(g[0][:2]): (g[0][2:],) + g[1:] for g in grouper(inputlist, 3)})
{'IND, MIA': (('05/30',), ('ND', '07/30'), ('UNA', 'ONA', '100')),
'LAA, SUN': (('05/30',), ('AA', 'SN', '07/29'), ('UAA', 'AAN'))}
from collections import defaultdict
def solve(lis, skip = 0):
dic = defaultdict(list)
it = iter(lis) # create an iterator
for elem in it:
key = ", ".join(elem[:2]) # create key
dic[key].append(elem)
for elem in xrange(skip): # append the next two items to the
dic[key].append(next(it)) # dic as skip =2
print dic
solve([('IND', 'MIA', '05/30'), ('ND', '07/30'), ('UNA', 'ONA', '100'), \
('LAA', 'SUN', '05/30'), ('AA', 'SN', '07/29'), ('UAA', 'AAN')], skip = 2)
輸出:
defaultdict(<type 'list'>,
{'LAA, SUN': [('LAA', 'SUN', '05/30'), ('AA', 'SN', '07/29'), ('UAA', 'AAN')],
'IND, MIA': [('IND', 'MIA', '05/30'), ('ND', '07/30'), ('UNA', 'ONA', '100')]
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.