尝试查找某项在另一个字符串列表中的列表中出现的次数



我有这个str列表和另一个搜索列表number:

animal = [[['cat', 'cat', 'dog'], ['cat', 'cat', 'dog'], ['cat', 'cat', 'dog']]
number = ['cat', 'dog']

我如何使它在python上,使它计算的次数,每个str内部的number可以在animal中找到?例如,"猫"的答案是6,"狗"的答案是3。我尝试使用count方法的列表,但它只工作,如果我有一个str,我需要它来搜索它使用列表。

我尝试做一个for循环(只针对第一个索引):

found = 0
for char in animal:
if str(number[0]) in str(animal):
found = found+1
return found

的问题是,我不能这样做,如果我有一个无限数量的str在数!如果我有10个str的数字我就必须对[0],[1],[2],[3],[4],[5],…这会花费很多时间。

你可以试试这个简单的Counter:


from collections import Counter
L =  ['cat', 'cat', 'dog']
to_search = ['cat', 'dog']
counts = Counter(L)       # a dictionary - find item is O(1) 
print(counts)

for item in to_search:
if item in counts:
print(item, counts[item])
输出:

cat 2
dog 1

如果你只对搜索一个单词/动物感兴趣,你可以这样做:

search_word  = 'cat'
print(counts[search_word])    # 2

你可以使用字典:

animal = ['cat', 'cat', 'dog']
number = ['cat', 'dog']
counter_dict = dict()
for value in animal:
#remove following 2 lines to count all unique values
if value not in number: 
continue #skip if not counting this value
#get() function returns None if the key wasn't created yet
#"or" part makes sure prev_count is number - None or 0 == 0
prev_count = counter_dict.get(value) or 0
counter_dict[value] = prev_count + 1
print(counter_dict)

输出:{'cat': 2, 'dog': 1}

注意:"或"窍门只工作,因为我想0是默认的:
None or x返回x,但0 or x也返回x。由于x在此特定情况下是0,因此没有区别。用

比较合适
prev_count = counter_dict.get(value)
counter_dict[value] = 1 if prev_count is None else (prev_count + 1)

但是那样看起来就不那么漂亮了

你可以尝试用简单的形式

list2 = ['cat', 'cat', 'dog']
number = ['cat', 'dog']

print([list2.count(j) for j in number])

输出
[2, 1] #2 is times he find the first value 'cat' inside list2

using pandas library without loops

list2 = ['cat', 'cat', 'dog']
number = ['cat', 'dog']
flatten_list = [['cat', 'cat', 'dog'], ['cat', 'cat', 'dog'], ['cat', 'cat', 'dog']]
import pandas as pd

from itertools import chain
def get(arr):

if type(arr[0])==list:
# if you have 2d array then make it 1d ex [[2],[4]] => [2,4]
arr = list(chain.from_iterable(arr))

counts = pd.Series(arr).value_counts() # return how many times the value repeated inside your array
print(counts)# print result without loop
# another way using loop same result
print([arr.count(j) for j in number])
get(flatten_list) 
get(list2) 

或与2 for循环的2d数组

print([sum(i == item for a in flatten_list for i in a) for item in number]) 

输出[6,3]

相关内容

  • 没有找到相关文章

最新更新