使用itertools
grouper
配方:
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'))}