简体   繁体   中英

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. 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.

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

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

{'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. 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)

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)

Try it online!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM