[英]How to find the number of times an item appears in a list of list of strings without using counter, or dictionary in python?
If I have如果我有
animal = [['cat', 'cat', 'dog'], ['cat', 'cat', 'dog'], ['cat', 'cat', 'dog']]
and和
item_to_find = ['cat', 'dog']
how do I calculate the number of times each string inside item_to_find
can be found in animal
?如何计算item_to_find
中的每个字符串可以在animal
中找到的次数? for example, for 'cat'
, the answer would be 6, and for 'dog'
it would be 3. I need to do this without using collectiouns.Counter
or a dictionary.例如,对于'cat'
,答案是 6,对于'dog'
,答案是 3。我需要在不使用collectiouns.Counter
或字典的情况下执行此操作。 I tried to use count
, but it only works if it's a list of strings, and not a list of list of strings.我尝试使用count
,但它仅适用于字符串列表,而不是字符串列表。
I tried to do it this way:我试着这样做:
for i in item_to_find:
print(animal.count(i))
but like I was saying this only works for a list of strings and not a list of list of strings.但就像我说的那样,这只适用于字符串列表,而不适用于字符串列表。
My result would look like something like this: [6, 3]
(as a list).我的结果看起来像这样: [6, 3]
(作为列表)。
Use sum
along with count
to sum up the counts in all the sub-lists:使用sum
和count
来总结所有子列表中的计数:
>>> animal = [['cat', 'cat', 'dog'], ['cat', 'cat', 'dog'], ['cat', 'cat', 'dog']]
>>> item_to_find = ['cat', 'dog']
>>> [(item, sum(a.count(item) for a in animal)) for item in item_to_find]
[('cat', 6), ('dog', 3)]
If you wanted to avoid using count
you can do it almost as easily by using a nested generator with sum
:如果您想避免使用count
,您可以通过使用带有sum
的嵌套生成器来轻松地做到这一点:
>>> [(item, sum(i == item for a in animal for i in a)) for item in item_to_find]
[('cat', 6), ('dog', 3)]
If you don't want to know which item each count goes with, make it a list of just the counts instead of a tuple that includes the item:如果您不想知道每个计数与哪个项目相关,请将其设为仅包含计数的列表,而不是包含该项目的元组:
>>> [sum(a.count(item) for a in animal) for item in item_to_find]
[6, 3]
You can use iteration:您可以使用迭代:
occurrences = [0] * len(item_to_find)
for sublist in animal:
for idx, item in enumerate(item_to_find):
occurrences[idx] += sublist.count(item)
Now occurrences will be [6, 3] for the example given.对于给出的示例,现在出现的次数将是 [6, 3]。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.