从列表创建字典

从此元组列表中:


[('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')]}

如果这有任何关系,则一旦有问题的值成为键,就可以将它们从元组中删除,因为从那以后我就不再需要它们了。任何建议,不胜感激!


慕尼黑的夜晚无繁华
浏览 176回答 3
3回答

www说

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

哆啦的时光机

使用itertools grouper配方:from itertools import izip_longestdef 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 defaultdictdef solve(lis, skip = 0):&nbsp; &nbsp; dic = defaultdict(list)&nbsp; &nbsp; it = iter(lis)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; # create an iterator&nbsp; &nbsp; for elem in it:&nbsp; &nbsp; &nbsp; &nbsp; key = ", ".join(elem[:2])&nbsp; &nbsp; &nbsp;# create key&nbsp; &nbsp; &nbsp; &nbsp; dic[key].append(elem)&nbsp; &nbsp; &nbsp; &nbsp; for elem in xrange(skip):&nbsp; &nbsp; &nbsp;# append the next two items to the&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; dic[key].append(next(it)) # dic as skip =2&nbsp;&nbsp; &nbsp; print dicsolve([('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'>,&nbsp;{'LAA, SUN': [('LAA', 'SUN', '05/30'), ('AA', 'SN', '07/29'), ('UAA', 'AAN')],&nbsp;'IND, MIA': [('IND', 'MIA', '05/30'), ('ND', '07/30'), ('UNA', 'ONA', '100')]&nbsp;})
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python