Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 给定字符串列表,返回出现在多个字符串中的字符_Python_Python 3.x_String_List_Set - Fatal编程技术网

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'}