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

2024-10-04 15:21:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一份清单: lst [a,b,c,d,e]

然后输入: food

我想要输出: there is 1 d

另一个输入示例: aachen

因此,输出为: there is 2 athere is 1 e

它的大小写不重要


Tags: 示例foodistherelstaachen
2条回答

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)

您可以使用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}")

相关问题 更多 >

    热门问题