在一组未知字符串中查找所有常用字母

2024-09-25 00:30:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我想创建一个函数,它将字符串列表作为参数,并且只返回所有字符串共用的那些字符。我想使用setAPI来实现这一点。你知道吗

例如:

my_words = ["house", "cheese", "helicopter"]

def FindCommonCharacters(my_words):
    xxxx

Output: {"e", "h"}

我知道如何做到这一点,如果我事先知道有多少字符串,我将在我的名单。因为这样我可以将每个字符串转换成一个集合,然后使用intersection操作。但是如果我不知道字符串的数目我不知道该怎么办。。。有什么想法吗?你知道吗

注意:我不能使用map或星号(*),正如我在类似问题中看到的那样。你知道吗


Tags: 函数字符串列表参数mydef字符house
2条回答

一种不使用*map的替代方法如下:

from functools import reduce

my_words = ["house", "cheese", "helicopter"]

my_sets = [set(w) for w in my_words]
head, tail = my_sets[0], my_sets[1:]
result = reduce(set.intersection, tail, head)

print(result)

上述方法可以考虑这个answer的函数版本。请注意,set.intersection是为更多的多个集合而设计的,如文档中所示:

Return a new set with elements common to the set and all others.

因此,为了完整起见,我包括以下两个例子:

my_words = ["house", "cheese", "helicopter"]
result = set.intersection(*(set(s) for s in my_words))

输出

{'h', 'e'}

正如@Jab所评论的,另一种方法是使用map:

result = set.intersection(*map(set, my_words))

也许是IIUC

my_words = ["house", "cheese", "helicopter"]

s = set(my_words[0])
for w in my_words[1:]:
    s = s.intersection(w)

# {'e', 'h'}

相关问题 更多 >