-
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): 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 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'>, {'LAA, SUN': [('LAA', 'SUN', '05/30'), ('AA', 'SN', '07/29'), ('UAA', 'AAN')], 'IND, MIA': [('IND', 'MIA', '05/30'), ('ND', '07/30'), ('UNA', 'ONA', '100')] })