2015-05-15 39 views
-1

我有字典清單:如何在Python中查找包含字典的列表的長度?

>>> Fruits = [{'apple': 'red', 'orange': 'orange'}, {'pear': 'green', 'cherry': 'red', 'lemon': 'yellow'}, {}, {}] 
>>> 
>>> len (Fruits) 
4 

List 0: {'orange': 'orange', 'apple': 'red'} 
List 1: {'cherry': 'red', 'lemon': 'yellow', 'pear': 'green'} 
List 2: {} 
List 3: {} 

雖然LEN(水果),並返回「正確」的長度,我不知道是否有一個快捷命令只返回,在他們有值列表的長度?

最終,我想做的事:

# Length Fruits is expected to be 2 instead of 4. 
for i in range (len (Fruits)): 
    # Do something with Fruits 
    Fruits [i]['grapes'] = 'purple' 
+0

你想在每個水果的dict即非空操作,或您使用我的一些有趣的事情? pythonic解決方案取決於你的意圖。有點像'我在範圍內(len(水果));水果[i] ['蘋果']'被認爲是反模式。 – munk

+0

可能重複的[對象列表中具有匹配屬性的Python計數元素](http://stackoverflow.com/questions/16455777/python-count-elements-in-a-list-of-objects-with-matching-屬性) – munk

+0

我使用「我」作爲索引來添加或刪除字典值。 – dreamzboy

回答

1

可以過濾掉空dict條目有兩種方法:

使用列表中理解和使用容器的感實性(這是True當且僅當它是非空)

>>> len([i for i in Fruits if i]) 
2 

使用filterNone過濾反對

>>> len(list(filter(None, Fruits))) 
2 
+0

這似乎是最短和最容易實現的。謝謝! – dreamzboy

3

您可以過濾空類型的字典,並檢查LEN或者乾脆使用sum添加1每個非空字典:

Fruits = [{'apple': 'red', 'orange': 'orange'}, {'pear': 'green', 'cherry': 'red', 'lemon': 'yellow'}, {}, {}] 

print(sum(1 for d in Fruits if d)) 
2 

if d會評估爲False任何空字典,所以我們正確地以2作爲長度。

如果你想從水果刪除空類型的字典:

Fruits[:] = (d for d in Fruits if d) 

print(len(Fruits)) 

Fruits[:]改變了最初的名單,(d for d in Fruits if d)generator expression很像sum例如,僅保留非空類型的字典。

然後遍歷列表,訪問類型的字典:

for d in Fruits: 
    # do something with each dict or Fruits 
2

你不需要len這裏,也不要range

for d in Fruits: 
    if not d: 
     continue 
    # do stuff with non-empty dict d 
+0

這將工作,但我需要迭代列表。然後我將不得不使用枚舉。儘管謝謝你的幫助。 – dreamzboy

相關問題