我希望能够打印列表中某个字符或单词的出现次数。
''' Python代码 '''
list_elem=['a','x','e','x','i','x','o','x','u']
count_of_element=list_elem.count('x')
print("Count of a particular element in the list is : ",count_of_element)
答案 0 :(得分:1)
使用collections.Counter
:
from collections import Counter
list_elem = ['a','x','e','x','i','x','o','x','u']
c = Counter(list_elem)
for k, v in c.items():
print(f"Count of {k} element in the list is : {v}")
输出:
Count of a element in the list is : 1
Count of x element in the list is : 4
Count of e element in the list is : 1
Count of i element in the list is : 1
Count of o element in the list is : 1
Count of u element in the list is : 1
答案 1 :(得分:0)
遍历列表中的每个项目,并检查其是否等于要查找的项目。数平等
def count(list_elem_to_find, lst):
count_of_item = 0
for item in lst:
if item == list_elem_to_find:
count_of_item += 1
return count_of_item
list_elem=['a','x','e','x','i','x','o','x','u']
count_of_x = count('x', list_elem)
print("Count of x in list: " + str(count_of_x))