简体   繁体   English

如何检查每个字母是否在多个字符串中?

[英]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:使用setreduce可能会有所帮助:

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.

相关问题 如何检查字符串列表中的字符串中是否存在大写字母? - How do I check if there is a uppercase letter in a string within a list of strings? 我如何检查一个字符串中是否有多个字母并识别这些出现中的每一个? - How can i check if there is a letter multiple times in a string and identify each of these occurances? 如何检查数组中每个项目的首字母? - How can I check the first letter of each item in an array? 如何更改网格(字符串数组)中的单个字母? - How do I change a single letter in a grid (array of strings)? 如何为每个大写字母分配数值? - How do I assign a numerical value to each uppercase Letter? 如何阻止每个字母打印在不同的行上? - How do I stop each letter from printing on different line? 如何检查字符串中的字符是否为非字母? - How do I check if a character in a string is a non-letter? 如何获得每个字母的协调并提取一个numpy数组中的字母? - How do I get the coordination of each letter and also extract the letter in a numpy array? 如何打印 python 中每个字符串的第一个字母、第二个字母和第三个字母? - How do I print the first letter and second letter and third.. of each string in python? 如何根据每行中的条件将多个字符串添加到 pandas dataframe 中的列中? - How do I add multiple strings to a column in a pandas dataframe based on conditions in each row?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM