Python:在列表中搜索值
我有以下设置:Python:在列表中搜索值,python,python-3.x,list,Python,Python 3.x,List,我有以下设置: 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
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:
我尝试搜索包含语法以与re
模块一起使用,但没有返回任何有用的内容
编辑#2:
对于这样的情况:
stuff = ['crabapple']
'apple' in stuff
False
“苹果”这个词确实存在,它只是另一个词的一部分。在这种情况下,我也想返回它。使用列表理解
print ([x for x in stuff if "orange" in x])
在中使用的方式不正确,应删除==True
,否则python将在二进制列表中将其视为“橙色”
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
使用以下命令:
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。字符串的find
方法返回子字符串的索引,如果未找到,则返回-1:
for s in stuff:
if s.find('orange') != -1:
print(s)
如果你在('orange'在stuff[x])
中添加一些括号会发生什么?
中的操作符已经返回布尔值,你不需要==True
Wim:你的解决方案奏效了,我猜这是因为没有括号,它想看看索引值x处的“stuff”是否等于True,你会说那是正确的吗?我会说那部分是正确的。您的问题实际上是由于意外的链式比较造成的,但我怀疑立即关闭副本不会对您有多大帮助。下面是Tim Peters给出的一个示例答案:关于直接更改Python中的行为的相关公开问题,因为它相对来说经常会让新用户绊倒:重新考虑包容测试的比较链接。请参见编辑#2对于编辑#2,它将只搜索列表中是否存在搜索字符串。是的,我的方法适用于“crabapple”中的“apple”。