📌  相关文章
📜  Python程序,用于查找字符串列表中常见元素的频率

📅  最后修改于: 2022-05-13 01:55:07.716000             🧑  作者: Mango

Python程序,用于查找字符串列表中常见元素的频率

给定的字符串列表。任务是找到字符串列表中给定的所有字符串中共有的元素的频率。

例子:

Input : test_list = ["gegek", "gfgk", "kingg"]
Output : {'g': 2, 'k': 1}
Explanation : g occurs twice in all Strings.

Input : test_list = ["gefgek", "gfgk", "kinfgg"]
Output : {'g': 2, 'k': 1, 'f' : 1}
Explanation : f occurs once in all Strings.

方法:使用reduce() + lambda + Counter()

以上功能的组合可以解决这个问题。在这里,我们使用 Counter() 执行计数的关键作用,并且使用 lambda 和 reduce() 分别对所有字符串执行逻辑的交集和扩展。

Python3
# Python3 code to demonstrate working of
# Strings list intersection
# Using reduce() + lambda + Counter()
from functools import reduce
from collections import Counter
 
# initializing list
test_list = ["geek", "gfgk", "king"]
 
# printing original list
print("The original list is : " + str(test_list))
 
# using & operator to perform intersection
res = reduce(lambda a, b: a & b, (Counter(ele) for ele in test_list[1:]),
             Counter(test_list[0]))
 
# printing result
print("String intersection and frequency : " + str(dict(res)))


输出
The original list is : ['geek', 'gfgk', 'king']
String intersection and frequency : {'g': 1, 'k': 1}