Python 给定字符串列表,返回出现在多个字符串中的字符
我试图实现一个函数,该函数接收可变数量的字符串,并返回至少出现在两个字符串中的字符:Python 给定字符串列表,返回出现在多个字符串中的字符,python,python-3.x,string,list,set,Python,Python 3.x,String,List,Set,我试图实现一个函数,该函数接收可变数量的字符串,并返回至少出现在两个字符串中的字符: test_strings = ["hello", "world", "python", ] print(test(*strings)) 删除字符串中的重复项(通过创建每个字符串的字符集),然后创建一个计数器,该计数器统计每个字符出现在其中的输入字符串的数量 from collections import Counter from itertools import chain def test(*strin
test_strings = ["hello", "world", "python", ]
print(test(*strings))
删除字符串中的重复项(通过创建每个字符串的字符集),然后创建一个计数器,该计数器统计每个字符出现在其中的输入字符串的数量
from collections import Counter
from itertools import chain
def test(*strings, n=2):
sets = (set(string) for string in strings)
counter = Counter(chain.from_iterable(sets))
return {char for char, count in counter.items() if count >= n}
print(test("hello", "world", "python")) # {'o', 'h', 'l'}
一个使用和:
输出:
>>> letters
{'o', 'l', 'h'}
from collections import Counter
test_strings = ["hello", "world", "python"]
letters = {k for k, v in Counter([l for x in test_strings for l in set(x)]).items() if v > 1}
>>> letters
{'o', 'l', 'h'}