如何在Python的列表元素中计算子字符串的实例?

问题描述 投票:0回答:1

该程序根据用户输入创建列表。然后,用户输入一个子字符串以在列表中进行搜索。我想计算子串出现在列表中的实例。例如:input_list = [python treeree 3 free]。 search_str ='ree'。总数应为4。

我已经尝试过使用sum()函数来获得正确的结果,但是我需要解析单词列表以进行作业分配。

total = 0
input_list = input('Type a list of words separated by a space: ')
search_str = str(input('Type a string to search for: '))
input_list = input_list.lower().split()
for x in input_list:
    if search_str in x:
        total = total + 1
print(search_str,": ",total)

代码运行,但是,不计算字符串出现的总数(即4),而是仅计算出现字符串的总数(即3)。

python-3.x list loops for-loop python-idle
1个回答
0
投票

如果允许使用count,则可以替换:

if search_str in x:
    total = total + 1

with:

total += x.count(search_str)

它将在search_str中计算x的所有实例,为您提供预期的结果。

© www.soinside.com 2019 - 2024. All rights reserved.