【发布时间】:2020-01-06 16:59:26
【问题描述】:
我正在尝试实现一个函数,它接收可变数量的字符串并返回至少出现在两个字符串中的字符:
test_strings = ["hello", "world", "python", ]
print(test(*strings))
{'h', 'l', 'o'}
【问题讨论】:
标签: python python-3.x string list set
我正在尝试实现一个函数,它接收可变数量的字符串并返回至少出现在两个字符串中的字符:
test_strings = ["hello", "world", "python", ]
print(test(*strings))
{'h', 'l', 'o'}
【问题讨论】:
标签: python python-3.x string list set
从字符串中删除重复项(通过设置每个字符串的字符集),然后创建一个 Counter 来计算每个字符出现在的输入字符串的数量
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'}
【讨论】:
使用sets 和collections.Counter 的单行代码:
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'}
【讨论】: