python编写代码以计算给定字符串中的重复字符,Python从其他字符串列表中计算列表中子字符串的数量,没有重复...

I have two list:

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

master_list = ['Smith', 'Roger']

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.

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

解决方案

A one liner

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

4

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值