![](/img/trans.png)
[英]How do I count word occurrence in each line if the word is in a dictionary
[英]I want to print each word and respective occurrence of that word/element in a list
我希望能够打印列表中某个字符或单词的出现次数。
'''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)
使用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
遍历列表中的每个项目,并检查其是否等于要查找的项目。 数平等
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))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.