1

从这个元组列表中:

[('IND', 'MIA', '05/30'), ('ND', '07/30'), ('UNA', 'ONA', '100'), \
('LAA', 'SUN', '05/30'), ('AA', 'SN', '07/29'), ('UAA', 'AAN')] 

我想创建一个字典,其中的键将是每三个 tuple[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')]}

如果这有任何相关性,一旦有问题的值成为键,它们可能会从元组中删除,从那时起我不再需要它们了。任何建议都非常感谢!

4

3 回答 3

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

字典理解解决方案是可能的,但有些混乱。

要从数组中删除键,请将第二个循环行 ( result[item[0]+ ...) 替换为

result[item[0]+","+item[1]] = [item[2:]]+inp[i+1:i+3]

听写理解解决方案(比我最初想象的要少一点:))

rslt = {
    inp[i][0]+", "+inp[i][1]: inp[i:i+3]
    for i in range(0, len(inp), 3)
}

并在答案中添加更多犹太洁食,这里有一些有用的链接:):defaultdictdict comprehensions

于 2013-05-31T20:18:11.697 回答
2

使用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'))}
于 2013-05-31T20:17:16.733 回答
1
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')]
 })
于 2013-05-31T20:45:01.510 回答