我想创建一个函数,它将字符串列表作为参数,并且只返回所有字符串共用的那些字符。我想使用set
API来实现这一点。你知道吗
例如:
my_words = ["house", "cheese", "helicopter"]
def FindCommonCharacters(my_words):
xxxx
Output: {"e", "h"}
我知道如何做到这一点,如果我事先知道有多少字符串,我将在我的名单。因为这样我可以将每个字符串转换成一个集合,然后使用intersection
操作。但是如果我不知道字符串的数目我不知道该怎么办。。。有什么想法吗?你知道吗
注意:我不能使用map
或星号(*),正如我在类似问题中看到的那样。你知道吗
一种不使用
*
或map
的替代方法如下:上述方法可以考虑这个answer的函数版本。请注意,set.intersection是为更多的多个集合而设计的,如文档中所示:
因此,为了完整起见,我包括以下两个例子:
输出
正如@Jab所评论的,另一种方法是使用map:
也许是IIUC
相关问题 更多 >
编程相关推荐