Python:在lis中搜索值

2024-03-29 11:18:16 发布

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

我有以下设置:

stuff = ['apple', 'I like apples today', 'orange', 'oranges and apples guys']

我想做的是:我想搜索列表中的每个值,看看单词“orange”是否包含在列表索引值中的任何位置。你知道吗

换句话说,我的预期输出是:

orange
oranges and apples guys

我现在得到的什么都不是。你知道吗

以下是我目前正在做的:

for x in range(0, len(stuff), 1):

     if 'orange' in stuff[x] == True:
          print('testing to see if this works')

我不成功,有什么建议吗?你知道吗

编辑#1:

我尝试搜索contains语法以用于re模块,但没有返回任何有用的内容。你知道吗

编辑#2:

对于这样的情况:

stuff = ['crabapple']

'apple' in stuff

False

“苹果”这个词确实存在,它只是另一个词的一部分。在这种情况下,我也要退回。你知道吗


Tags: andin编辑apple列表todayif情况
3条回答

使用此选项:

for x in range(0, len(stuff), 1):
    if ('orange' in stuff[x])== True:
        print('testing to see if this works')

对于您的代码,python将判断'stuff[x]==True'(它将是False),然后判断'orange in False',因此它将始终是False。你知道吗

在中使用的方式不正确,应删除==True,否则python将在二进制列表中将其视为“orange”。你知道吗

for x in stuff:
    if 'orange' in x:
        print('testing to see if this works\n')
        print(x)

testing to see if this works

orange
testing to see if this works

oranges and apples guys

使用列表理解

print ([x for x in stuff if "orange" in x])

相关问题 更多 >