Python从其他字符串列表中计算列表中子字符串的数量,没有重复 [英] Python Count the number of substring in list from other string list without duplicates

查看:329
本文介绍了Python从其他字符串列表中计算列表中子字符串的数量,没有重复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个列表:

main_list = ['Smith', 'Smith', 'Roger', 'Roger-Smith', '42']
master_list = ['Smith', 'Roger']

我想计算从main_list字符串中的master_list中找到一个字符串的次数,而无需计算两次相同项.

I want to count the number of times I find a string from master_list in a string of main_list without counting two times the same item.

示例:对于上面的两个列表,我的函数的结果应为4."Smith"可以在main_list中检索3次. "Roger可以被发现2次,但由于在'Roger-Smith'中已经找到'Smith',因此该数字不再计数,因此'Roger'仅被算作1,总共4个.

Example: for the two lists above, the result of my function should be 4. 'Smith' can be retrieved 3 times in main_list. 'Roger can be found 2 times but as 'Smith' was already found in 'Roger-Smith', this one doesn't count anymore, so 'Roger' is just count as 1 which make 4 in total.

我写过的函数在下面,但是我认为有一种更快的方法:

The function I wrote for know is below but I think there is a faster way to do it:

def string_detection(master_list, main_list):
    count = 0
    for substring in master_list:
        temp = list(main_list)
        for string in temp:
            if substring in string:
                main_list.remove(string)
                count+=1
    return count

推荐答案

一个衬里

>>>sum(any(m in L for m in master_list) for L in main_list)
4

遍历main_list,并检查master_list中值的any是否在该字符串中.这将为您提供bool值列表.找到一个后它将停止,因此每个字符串的计数仅增加一个.方便地,sum对所有True进行计数以提供计数.

Iterate over main_list and check if any of the values from master_list are in that string. This leaves you with a list of bool values. It will stop after it finds one and so adds only one to the count for each string. Conveniently sum counts all the Trues to give you the count.

这篇关于Python从其他字符串列表中计算列表中子字符串的数量,没有重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆