[英]How do I check if each letter is in multiple strings?
I have an array:我有一个数组:
arr = ['ab', 'ac']
I want to check which letters are repeated for all items in arr.我想检查 arr 中的所有项目都重复了哪些字母。 For the above, 'a' is in both.
对于上述情况,“a”在两者中都有。 I would then want to print '1'.
然后我想打印'1'。
Another example would be:另一个例子是:
arr = ['abc', 'dca', 'ac']
'a' and 'c' are common to all, so I would print 2. 'a' 和 'c' 对所有人来说都是通用的,所以我会打印 2。
Any idea how to do this?知道怎么做吗?
You can make a set of the letters of each string, and determine the intersection of all sets:您可以制作一组每个字符串的字母,并确定所有集合的交集:
arr = ['abc', 'dca', 'ac']
common = set.intersection(*(set(string) for string in arr))
print(common)
# {'a', 'c'}
print(len(common))
# 2
set.intersection
accepts any number of arguments, we use the *
to unpack the generator expression yielding the sets. set.intersection
接受任意数量的 arguments,我们使用*
解包生成器表达式产生集合。
You can convert your entries into sets, then find their intersection:您可以将条目转换为集合,然后找到它们的交集:
arr = ['abc', 'dca', 'ac']
set_list = [set(a) for a in arr]
intersection = set.intersection(*set_list)
print(intersection)
print(len(intersection))
Output: Output:
{'c', 'a'}
2
References:参考:
here i converted the first element of list to to set for using thee intersection and it worked pretty good在这里,我将列表的第一个元素转换为设置以使用你的交集,它工作得很好
list_of_sets=['acb', 'ac']
print(len(set(list_of_sets[0]).intersection(*list_of_sets[1:])))
Using set
and reduce
could help out here:使用
set
和reduce
可能会有所帮助:
from functools import reduce
print(len(reduce(lambda x,y: set.intersection(set(x),set(y)),arr)))
ouputs输出
2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.