2016-03-28 45 views
0
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)]) 

如果所有值都tupled或上市沒有問題。

+3

爲什麼這是預期的輸出?每個鍵只能有一個值,此時您將*替換上一個值。 – jonrsharpe

+0

是的預期輸出應該包括所有相應的值,但不知道如何去做。 – jean

+3

你需要仔細檢查你的代碼,並理解'd [i] = j'實際上在你的代碼中做了什麼。看看你期待的數據結構。看看你在做什麼。確定如何在更新字典中的值的上下文中正確創建該數據結構。使用文檔盧克。 – idjaw

回答

5

不是每次都來取代值,將其添加到元組:

>>> 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 s爲不可變的,每次追加創建一個新對象。如果您使用list s,這將更有效率。

+0

是的列表也可以。 – jean

+0

如何做列表? – jean

+1

@jean:'for i,j in l:d.setdefault(i,[])。append(j)' – GingerPlusPlus

1

下面是一個使用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])]) 
1
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)]) 
+0

如果是tupled或列出。 – jean

+0

如果不是isinstance(d [i],tuple),那麼這將會更加可讀,而不是使用'lambda':'d [i] =(d [i],)' –

+0

謝謝,我編輯我的回覆 – aless80