python - 只打印包含特定字符的列表项

标签 python list python-3.4

如果字符串以某个字符开头并且在字符串中重复,我会尝试将计数加一。这是我的代码

def stringMatch(list1, char):
    count = 0
    for i in range(len(list1)):
        if char == list1[i][:]:
            count = count + 1 
            print(list1[i], count)

对于输入 list1 = ['cat', 'dog', 'corn']char = 'c'

输出应该是

cat 1
corn 1 

最佳答案

在您的代码中,您使用if char == list1[i][:]。这会导致您的问题。

list1[i][:]list1[i] 相同,这实际上不是您想要做的。您不想查看 list1[i] 是否为 char;相反,您想知道 list1[i] 包含 char。您可以通过多种方式来实现这一目标。以下是三个:

  1. list1[i]中的字符
  2. 这个for循环:
found = False
for c in list1[i]:
    if c == char:
        found = True
        break
  • 如果有(list1[i] 中的 c 为 char==c)
  • 无论如何,这就是我要做的:

    def stringMatch(L, char):
        counts = (char in word for word in L)  # compute the counts of `char` in each list item
        for word, count in zip(L, counts):
            if not count: continue
            print(word, count)
    

    关于python - 只打印包含特定字符的列表项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32599481/

    相关文章:

    linux - 导入错误 : No module named matplotlib with matplotlib installed

    Python多处理一次读取输入迭代器

    Python 不返回任何 MySQL 结果

    python - 更改文件夹中 csv 文件的名称

    python - 使用 ffmpeg-python 为视频添加多个字幕

    Java 如何在对象列表中保持唯一值

    Python - 用列表提供对象

    Perl:展平多维数组的最简单方法是什么?

    python - Pyaudio - 将声音数据转换为字符串的算法

    python - 一个非常短的代码,但 python 中的语法无效?