2016-01-12 59 views
0

簡單的例子這裏字典的增量值:的Python:存儲在一個列表

我想有這充滿字典對於每一個類型的動物名單。

打印應該是這樣的:

dictlist_animals = [{'type':'horse','amount':2}, 
        {'type':'monkey','amount':2}, 
        {'type':'cat','amount':1}, 
        {'type':'dog','amount':1}] 

因爲有些動物存在我不止一次添加了一個名爲「量」,這應該算作是如何存在的每一種類型的許多動物關鍵更多。

我不確定'if-case'是否正確,我在'else case'中寫什麼?

dictlist_animals = [] 

animals = ['horse', 'monkey', 'cat', 'horse', 'dog', 'monkey'] 


for a in animals: 
    if a not in dictlist_animals['type']: 
     dictlist_animals.append({'type': a, 'amount' : 1}) 

    else: 
     #increment 'amount' of animal a 

回答

4

更好地使用Counter。它創建字典,其中鍵是動物列表的元素,值是它們的數量。然後你可以使用列表理解與詞典創建列表:

from collections import Counter 

animals_dict = [{'type': key, 'amount': value} for key, value in Counter(animals).items()] 
1

嘗試下面的代碼,

dictlist_animals = [] 

animals = ['horse', 'monkey', 'cat', 'horse', 'dog', 'monkey'] 
covered_animals = [] 
for a in animals: 
    if a in covered_animals: 
     for dict_animal in dictlist_animals: 
      if a == dict_animal['type']: 
       dict_animal['amount'] = dict_animal['amount'] + 1 
    else: 
     covered_animals.append(a) 
     dictlist_animals.append({'type': a, 'amount' : 1}) 
print dictlist_animals 

[{'amount': 2, 'type': 'horse'}, {'amount': 2, 'type': 'monkey'}, {'amount': 1, 'type': 'cat'}, {'amount': 1, 'type': 'dog'}] 
1

名單上你不能直接調用dictlist_animals['type']因爲他們是數字索引。你可以做的就是這個數據存儲在中間字典,然後將其轉換成數據結構,你想:

dictlist_animals = [] 

animals = ['horse', 'monkey', 'cat', 'horse', 'dog', 'monkey'] 

animals_count = {}; 
for a in animals: 
    c = animals_count.get(a, 0) 
    animals_count[a] = c+1 

for animal, amount in animals_count.iteritems(): 
    dictlist_animals.append({'type': animal, 'amount': amount}) 

注意c = animals_count.get(a, 0)將獲取動物a如果它存在的電流量,否則返回默認值0,這樣就不必使用if/else語句。

1

您也可以使用defaultdict

from collections import defaultdict 
d = defaultdict(int) 
for animal in animals: 
    d[animal]+= 1 

dictlist_animals = [{'type': key, 'amount': value} for key, value in d.iteritems()]