首页 > 解决方案 > 查找列表中给出的 n 个字符串列表中有多少个字符?

问题描述

我有这两个清单

['lfhtzrxcj', 'fbtzlhrcj', 'lzdaftrjphco']

['a', 'b', 'c', 'd', 'f', 'h', 'j', 'l', 'o', 'p', 'r', 't', 'x', 'z']

我需要找出第二个列表中有多少个字母在第一个列表的所有字符串中。

我不知道怎么做...

标签: pythonlist

解决方案


这可能不是最漂亮的代码,但它可以工作:

def count_letters (letter_list, word_list):
    # creating a list of counters for each letter you want to count
    counter_list =[]
    i= 0
    for i in letter_list:
        counter_list.append(0)
    # counting how many times each letter is in a word
    for word in word_list:
        #print(word)
        i = 0
        for l in letter_list:
            counter_list[i]+=word.count(l)
            i=i+1
        #print(letter_list)
    print(counter_list)
    return counter_list

使用您的示例:

a = ['a', 'b', 'c', 'd', 'f', 'h', 'j', 'l', 'o', 'p', 'r', 't', 'x', 'z']
word_list = ['lfhtzrxcj', 'fbtzlhrcj', 'lzdaftrjphco']

count_letters(a,word_list)

您会得到以下输出:

[1, 1, 3, 1, 3, 3, 3, 3, 1, 1, 3, 3, 1, 3]

推荐阅读