繁体   English   中英

如何检查字符串是否包含列表并在python中显示

[英]How to check if string contain list and show it in python

我有列表: lst [a,b,c,d,e]

然后输入: food

我想要输出: there is 1 d

另一个输入示例: aachen

所以输出是: there is 2 a there is 1 e

大写或小写都没有关系。

您可以使用collections.Counter()来计算每个字母的出现次数,然后遍历您的lst并输出每个数字出现的次数。

import collections

lst = ['a','b','c','d','e']

word = 'food'

word_count = collections.Counter(word)

for letter in lst:
    count = word_count.get(letter)
    if count:
        print(f"There is {count} {letter}")

Python原生方式:

l = ['a','b','c','d','e']
m = {}
s = input("Enter input string:")
for f in l:
  for k in range(len(s)):
    if f == s[k]:
      if f in m:
        m[f] = m[f] + 1 
      else:
        m[f] = 1

for j in m.keys():
  print(s,"has")
  print(m[j],j)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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