Python 中統計列表中包含給定元素的子列表個數


給定列表中的元素也可能作為另一個字串存在於另一個變數中。在本文中,我們將瞭解給定流在一個給定列表中出現的次數。

使用 range 和 len

我們使用 range 和 len 函式來跟蹤列表的長度。然後使用 in 條件查詢字串作為列表元素出現的次數。一個初始化為零的計數變數在滿足條件時會遞增。

示例

 線上演示

Alist = ['Mon', 'Wed', 'Mon', 'Tue', 'Thu']
Bstring = 'Mon'

# Given list
print("Given list:\n", Alist)
print("String to check:\n", Bstring)
count = 0
for i in range(len(Alist)):
   if Bstring in Alist[i]:
      count += 1
print("Number of times the string is present in the list:\n",count)

輸出

執行上述程式碼將得到以下結果:

Given list:
['Mon', 'Wed', 'Mon', 'Tue', 'Thu']
String to check:
Mon
Number of times the string is present in the list:
2

使用 sum

我們使用 in 條件來匹配給定列表中的字串元素。最後應用 sum 函式來獲取匹配條件為正時的計數。

示例

 線上演示

Alist = ['Mon', 'Wed', 'Mon', 'Tue', 'Thu']
Bstring = 'Mon'
# Given list
print("Given list:\n", Alist)
print("String to check:\n", Bstring)
count = sum(Bstring in item for item in Alist)
print("Number of times the string is present in the list:\n",count)

輸出

執行上述程式碼將得到以下結果:

Given list:
['Mon', 'Wed', 'Mon', 'Tue', 'Thu']
String to check:
Mon
Number of times the string is present in the list:
2

使用 Counter 和 chain

itertools 和 collections 模組提供了 chain 和 counter 函式,可用於計算與字串匹配的列表中所有元素的個數。

示例

 線上演示

from itertools import chain
from collections import Counter
Alist = ['Mon', 'Wed', 'Mon', 'Tue', 'Thu']
Bstring = 'M'
# Given list
print("Given list:\n", Alist)
print("String to check:\n", Bstring)
cnt = Counter(chain.from_iterable(set(i) for i in Alist))['M']
print("Number of times the string is present in the list:\n",cnt)

輸出

執行上述程式碼將得到以下結果:

Given list:
['Mon', 'Wed', 'Mon', 'Tue', 'Thu']
String to check:
M
Number of times the string is present in the list:
2

更新於:2020年6月4日

344 次瀏覽

啟動您的 職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.