Python 中滿足特定條件的元素計數
在本文中,我們將瞭解如何從 Python 列表中獲取一些選定的元素。因此,我們需要設計一些條件,並且只有滿足該條件的元素才會被選中,並列印它們的計數。
使用 in 和 sum
在這種方法中,我們使用 in 條件來選擇元素,並使用 sum 來獲取它們的計數。如果元素存在,則使用 1,否則對於 in 條件的結果,使用 0。
示例
Alist = ['Mon', 'Wed', 'Mon', 'Tue', 'Thu'] # Given list print("Given list:\n", Alist) cnt = sum(1 for i in Alist if i in('Mon','Wed')) print("Number of times the condition is satisfied in the list:\n",cnt)
輸出
執行以上程式碼將得到以下結果:
Given list: ['Mon', 'Wed', 'Mon', 'Tue', 'Thu'] Number of times the condition is satisfied in the list: 3
使用 map 和 lambda
這裡也使用了 in 條件,但也使用了 lambda 和 map 函式。最後,我們應用 sum 函式來獲取計數。
示例
Alist = ['Mon', 'Wed', 'Mon', 'Tue', 'Thu'] # Given list print("Given list:\n", Alist) cnt=sum(map(lambda i: i in('Mon','Wed'), Alist)) print("Number of times the condition is satisfied in the list:\n",cnt)
輸出
執行以上程式碼將得到以下結果:
Given list: ['Mon', 'Wed', 'Mon', 'Tue', 'Thu'] Number of times the condition is satisfied in the list: 3
使用 reduce
reduce 函式將特定函式應用於作為引數提供給它的列表中的所有元素。我們將其與 in 條件一起使用,最終生成匹配條件的元素的計數。
示例
from functools import reduce Alist = ['Mon', 'Wed', 'Mon', 'Tue', 'Thu'] # Given list print("Given list:\n", Alist) cnt = reduce(lambda count, i: count + (i in('Mon','Wed')), Alist, 0) print("Number of times the condition is satisfied in the list:\n",cnt)
輸出
執行以上程式碼將得到以下結果:
Given list: ['Mon', 'Wed', 'Mon', 'Tue', 'Thu'] Number of times the condition is satisfied in the list: 3
廣告