如何在列表中搜索字符串并输出包含该字符串的所有值?

2024-10-03 04:29:50 发布

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

我希望能够看到一个字符串是否在我的列表中,然后打印列表中包含该字符串的所有项目。你知道吗

我发现[s for s in y if any(xs in s for xs in topcolour)]可以使用,当我只在列表中查找数字时,这种方法非常有效,但当我尝试查找颜色(蓝色、红色、黄色或绿色)时,它告诉我可以找到颜色,然后只打印出整个列表,而不是列表中的单个项目,就像它对数字所做的那样。供您参考,每张游戏的头号和头彩都会改变。你知道吗

if any(topnumber in s for s in p1cards):
    matching = [s for s in p1cards if any(xs in s for xs in topnumber)]
    print(matching) #this one works

elif any(topcolour  in s for s in p1cards):
    matching = [s for s in p1cards if any(xs in s for xs in topcolour)]
    print(matching) #this one doesn't work

如果可以找到,第一个代码块输出列表中的确切项目,例如["Blue 7"]如果topnumber是7,但是当我尝试按颜色搜索时,它只输出整个列表。你知道吗


Tags: 项目字符串in列表forif颜色any
1条回答
网友
1楼 · 发布于 2024-10-03 04:29:50

如果没有明确的输入和输出示例,很难判断这是否正是您要做的,但我认为它是基于您所提供的。你知道吗

我个人觉得嵌套理解很难理解,你不需要它们。^{}是一种很好的functional方法,用于检索满足特定条件的集合成员。^{}不是必须的,您可以定义一行函数并将它们作为第一个参数传递,但这对于这样的非常简单的测试是很好的。你知道吗

p1cards = {'Pick colour', 'Red 1', 'Yellow 5', 'Red 9', 'Blue skip', 'Blue 6'}

topnumber = '9'

print(tuple(
    filter(
        lambda c: topnumber in c,
        p1cards,
    )
))

topcolour = 'Red'

print(tuple(
    filter(
        lambda c: topcolour in c,
        p1cards,
    )
))

输出:

('Red 9',)
('Red 1', 'Red 9')

注意:tuple调用仅用于显示。如果您在Python2.x中运行它,就不需要它们;在3.x中,如果没有它们,就不会得到有用的输出。

相关问题 更多 >