[英]How to find sequence of letters in a list of strings?
Let's say I have the list:假设我有清单:
lst1 = ['abc', 'abcde', 'abab', 'acd']
I want to create a dictionary to count the # of times 'ab' is in the list, so in this example, the dictionary would be {'ab': 4}
.我想创建一个字典来计算 'ab' 在列表中出现的次数,所以在这个例子中,字典是{'ab': 4}
。 What do I do?我该怎么办?
You can use the following:您可以使用以下内容:
>>> {'ab': ','.join(l).count('ab')}
{'ab': 4}
You could use a generator expression within sum
您可以在sum
中使用生成器表达式
>>> lst1 = ['abc', 'abcde', 'abab', 'acd']
>>> {'ab': sum(1 for i in lst1 if 'ab' in i)}
{'ab': 3}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.