[英]Print items in a list which all contain at least one same character
I want to write a function which prints the items in a list that all contain at least one similar character and the amount of times it appears in each item.我想写一个 function 打印列表中的项目,这些项目都包含至少一个相似的字符以及它在每个项目中出现的次数。 For example if I had the following list:例如,如果我有以下列表:
ex = ['bat', 'cat', 'task', 'tank', 'tan']
Each item contains the letter 'a' and 't' at least once.每个项目至少包含一次字母“a”和“t”。
I know I could use我知道我可以使用
for string in ex:
for letter in string:
x = string.count("a")
print(string, "has", x, "a")
for string in ex:
for letter in string:
x = string.count("t")
print(word, "has", x, "t")
How would I do this without specifying the actual characters to search for like above, in case I would like to change the list?如果我想更改列表,我将如何在不指定要搜索的实际字符的情况下执行此操作?
using dictionary
使用dictionary
example = ['bat', 'cat', 'task', 'tank', 'tan']
d = {}
for val in example:
for element in val:
if element in d.keys():
d[element] = d[element] + 1
else:
d[element] = 1
print(d)
output output
{'b': 1, 'a': 5, 't': 5, 'c': 1, 's': 1, 'k': 2, 'n': 2}
Here is a simple code:)这是一个简单的代码:)
from functools import reduce
ex = ["bat", "cat", "task", "tank", "tan"]
reduce(lambda a,b: a.intersection(b) ,[set(e) for e in ex])
If you convert each word to a set of characters with [set(x) for x in ex]
, you can use set.intersection()
to return a set of characters that all the words have in common.如果使用[set(x) for x in ex]
将每个单词转换为一组字符,则可以使用set.intersection()
返回一组所有单词共有的字符。 Then for every letter, you can repeat your code.然后对于每个字母,您可以重复您的代码。
ex = ['bat', 'cat', 'task', 'tank', 'tan']
common_letters = set.intersection(*[set(x) for x in ex])
for letter in common_letters:
for string in ex:
x = string.count(letter)
print(string, "has", x, letter)
You could do this ( json
library is only used here for pretty print)你可以这样做( json
库仅用于漂亮的打印)
import json
arr = ['bat', 'cat', 'task', 'tank', 'tan']
letters = set(''.join(arr))
d = {}
for letter in letters:
d[letter] = {'words' : [], 'counts' : []}
for letter in letters:
for word in arr:
if letter in word:
d[letter]['words'].append(word)
d[letter]['counts'].append(word.count(letter))
pretty = json.dumps(d, indent=4)
print(pretty)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.