簡體   English   中英

如何在Python中查找包含字典的列表的長度?

[英]How to Find The Length of a List Containing Dictionary in 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(Fruits)確實返回了“正確”的長度,但是我想知道是否有一個快捷命令僅返回其中包含值的列表的長度?

最終,我想做:

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

您可以過濾空字典並檢查len,也可以對每個非空字典使用sum1

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)則為(d for d in Fruits if d)是一個生成器表達式 ,類似於sum例子,僅保留非空字典。

然后遍歷列表並訪問字典:

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

您根本不需要len ,也不需要range

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

您可以通過以下任一方法過濾掉空的dict條目:

使用列表推導並使用容器的真實性(如果非空,則為True

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

使用filterNone以對過濾器

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM