Python – 出现在多个字符串中的字符
有时,在使用Python字符串时,我们可能会遇到需要提取出现在字符列表中多个字符串中的字符串的问题。此类问题通常发生在 Web 开发和数据科学领域。让我们讨论可以执行此任务的某些方式。
方法 #1:使用Counter() + set()
这是可以执行此任务的方式之一。在此,我们检查所有字符串并计算每个字符串中的字符频率并返回出现多个字符串的字符。
# Python3 code to demonstrate working of
# Characters occurring in multiple Strings
# Using Counter() + set()
from itertools import chain
from collections import Counter
# initializing list
test_list = ['gfg', 'is', 'best', 'for', 'geeks', 'and', 'cs']
# printing original list
print("The original list is : " + str(test_list))
# Characters occurring in multiple Strings
# Using Counter() + set()
temp = (set(sub) for sub in test_list)
cntr = Counter(chain.from_iterable(temp))
res = [chr for chr, count in cntr.items() if count >= 2]
# printing result
print("Characters with Multiple String occurrence : " + str(res))
输出 :
The original list is : [‘gfg’, ‘is’, ‘best’, ‘for’, ‘geeks’, ‘and’, ‘cs’]
Characters with Multiple String occurrence : [‘g’, ‘e’, ‘f’, ‘s’]
方法 #2:使用列表理解 + Counter() + set()
这是可以执行此任务的方式之一。在此,我们执行与上述类似的任务,不同之处在于我们使用列表理解以紧凑和单线的方式执行。
# Python3 code to demonstrate working of
# Characters occurring in multiple Strings
# Using list comprehension + Counter() + set()
from itertools import chain
from collections import Counter
# initializing list
test_list = ['gfg', 'is', 'best', 'for', 'geeks', 'and', 'cs']
# printing original list
print("The original list is : " + str(test_list))
# Characters occurring in multiple Strings
# Using list comprehension + Counter() + set()
res = [key for key, val in Counter([ele for sub in test_list
for ele in set(sub)]).items()
if val > 1]
# printing result
print("Characters with Multiple String occurrence : " + str(res))
输出 :
The original list is : [‘gfg’, ‘is’, ‘best’, ‘for’, ‘geeks’, ‘and’, ‘cs’]
Characters with Multiple String occurrence : [‘g’, ‘e’, ‘f’, ‘s’]