将项目放入词典而不更改ord

2024-06-02 13:34:07 发布

您现在位置:Python中文网/ 问答频道 /正文

from collections import OrderedDict

l = [('Monkey', 71), ('Monkey', 78), ('Ostrich', 80), ('Ostrich', 96), ('Ant', 98)]

d = OrderedDict()
for i, j in l:
    d[i] = j
print d
OrderedDict([('Monkey', 78), ('Ostrich', 96), ('Ant', 98)])

预期的“d”应该是:

OrderedDict([('Monkey', (71,78)), ('Ostrich', (80,96)), ('Ant', 98)])

如果所有值都是元组或列表,则没有问题。你知道吗


Tags: infromimport列表forcollectionsmonkeyordereddict
3条回答

下面是一种使用groupby的方法:

from itertools import groupby

l = [('Monkey', 71), ('Monkey', 78), ('Ostrich', 80), ('Ostrich', 96), ('Ant', 98)]
                # Key is the animal, value is a list of the available integers obtained by
d = OrderedDict((animal, [i for _, i in vals])
                for (animal, vals) in
                # Grouping your list by the first value inside animalAndInt, which is the animal
                groupby(l, lambda animalAndInt: animalAndInt[0]))
# If you want a tuple, instead of [i for _, i in vals] use tuple(i for _, i in vals)
print(d)
>>> OrderedDict([('Monkey', [71, 78]), ('Ostrich', [80, 96]), ('Ant', [98])])
for i, j in l:
    if i in d:
        #d[i] = (lambda x: x if type(x) is tuple else (x,))(d[i])
        #Eugene's version:
        if not isinstance(d[i], tuple): 
             d[i] = (d[i],)
        d[i] += (j,)
    else:
        d[i] = j

给出以下内容。注意,'Ant'中的98并不像原来的问题那样是“tupled”。你知道吗

OrderedDict([('Monkey', (71, 78)), ('Ostrich', (80, 96)), ('Ant', 98)])

不是每次都替换值,而是将其添加到元组:

>>> l = [('Monkey', 71), ('Monkey', 78), ('Ostrich', 80), ('Ostrich', 96), ('Ant', 98)]
>>> d = OrderedDict()
>>> for i, j in l:
...     if i in d:
...         d[i] += (j,)
...     else:
...         d[i] = (j,)
... 
>>> d
OrderedDict([('Monkey', (71, 78)), ('Ostrich', (80, 96)), ('Ant', (98,))])

顺便说一句,因为tuple是不可变的,所以每次追加都会创建一个新对象。如果您使用lists,这将更有效

相关问题 更多 >