[英]Count the amount of lists in a list (nested list) for each length Python
我有一個包含字符串的列表列表。 如下所示:
[['apple', 'pear', 'apple'], ['apple', 'apple'], ['apple', 'pear', 'apple','apple', 'pear', 'apple']]
此列表中有大約 2000 個列表,所有列表都包含不同數量的字符串。 我想看看這個列表中有多少特定長度的子列表。 如下所示:
長度 2 個字符串:70 個列表長度 3 個字符串:45 個列表等等。
執行此操作的一種邏輯方法(我認為)是為一段渴望的長度制作一個循環,然后為我想要的列表數量的所有長度播放這個循環。
我會想象它是這樣的:
def countList(lst, x):
count = 0
for i in range(len(lst)):
if x in lst[i]:
count+= 1
return count
x = .....
但我不確定,因為我不知道如何讓它計算數量。
如果有人可以請幫助我,那就太好了!
您可以將長度傳遞給collections.Counter
,例如:
from collections import Counter
l = [['apple', 'pear', 'apple'], ['apple', 'apple'],['apple', 'apple'],['apple', 'apple'], ['apple', 'pear', 'apple','apple', 'pear', 'apple'], ['apple', 'pear', 'apple']]
counts = Counter(map(len,l))
並獲取字典counts
,例如:
Counter({3: 2, 2: 3, 6: 1})
長度為 3 的有 2 個,長度為 2 的有 3 個,長度為 6 的有 1 個。
您可以像訪問任何字典一樣訪問計數:
>> counts[2]
3
內置的collections.Counter
優雅地處理這個問題:
>>> from collections import Counter
>>> mydata = [['apple', 'pear', 'apple'], ['apple', 'apple'], ['apple', 'pear', 'apple','apple', 'pear', 'apple']]
>>> Counter(map(len, mydata))
Counter({3: 1, 2: 1, 6: 1})
>>> Counter(len(sublist) for sublist in mydata) # or with a generator expression
Counter({3: 1, 2: 1, 6: 1})
lst = [['apple', 'pear', 'apple'], ['apple', 'apple'], ['apple', 'pear', 'apple','apple', 'pear', 'apple'],['apple', 'apple']]
def countList(lst):
lst_dict = {}
for i in lst:
if len(i) not in lst_dict:
lst_dict[len(i)] = 1
else:
lst_dict[len(i)] = lst_dict[len(i)]+1
return lst_dict
print(countList(lst))
>> {3: 1, 2: 2, 6: 1}
這里的鍵是列表的長度,值是列表的數量。
lst = [['apple', 'pear', 'apple'], ['apple', 'apple'], ['apple', 'pear', 'apple','apple', 'pear', 'apple'], ['mango', 'apple'], ['mango', 'mango']]
ctr_dict = {}
for i in lst:
item_length = len(i)
if str(item_length) in ctr_dict:
ctr_dict[str(item_length)] = ctr_dict[str(item_length)] + 1
else:
ctr_dict[str(item_length)] = 1
for k,v in ctr_dict.items():
print(k," strings:", v, "lists")
output:
3 strings: 1 lists
2 strings: 3 lists
6 strings: 1 lists
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.