【发布时间】:2018-08-11 16:12:53
【问题描述】:
我有以下代码:
word = ""
if (letter=="a" for letter in word):
print("a found!")
即使 word 变量为空,它也会打印 a found!。为什么会这样?什么是做我想做的事情的正确方法?
【问题讨论】:
标签: python string python-3.x if-statement
我有以下代码:
word = ""
if (letter=="a" for letter in word):
print("a found!")
即使 word 变量为空,它也会打印 a found!。为什么会这样?什么是做我想做的事情的正确方法?
【问题讨论】:
标签: python string python-3.x if-statement
您在if 中使用的条件会返回一个生成器表达式<generator object <genexpr> at 0xefd89660>,它始终是True。
要验证您的条件返回什么,
print(letter=="a" for letter in word)
# <generator object <genexpr> at 0xefd89660>
因此你得到你所得到的。
正道:
word = ""
for x in word:
if x == 'a':
print('a found!')
遍历word,比较它是否等于'a',如果满足条件则执行任何操作。
甚至更好:
if 'a' in word:
print('a found!')
【讨论】:
这是因为(letter=="a" for letter in word) 语句是一个生成器。您的 if 语句检查该生成器是否是“真实”对象(为了方便起见,python 中的很多东西都评估为 true - 非空列表、非空字符串等),然后打印 "a found!",因为生成器评估为 @987654323 @。
相反,您可能想要以下内容。
word = ""
letter = "a"
if letter in word:
print(f"{letter} found!")
【讨论】:
(letter=="a" for letter in word) 返回一个生成器。由于生成器似乎没有 __len__ 或 __bool__ 它总是评估为 true。
你想要的代码是这个:
word = ""
if ("a" in word):
print("a found!")
【讨论】:
其实你可以用
for a in word:....
但如果你坚持你的方式,你应该写如下:
import numpy as np
word = "abc"
if np.any(list(letter=="a" for letter in word)):
print("a found!")
从生成器中提取元素,并使用 np.any() 来获取结果。
【讨论】:
以前的答案解释了它为什么不起作用,这只是一种使用列表理解来解决您的问题的方法:
word = "StackOverflow"
[print(letter + " found in:", word) for letter in word if letter == "a"]
返回:
a found in: StackOverflow
【讨论】: