Python,如果条件未按预期工作

时间:2018-08-11 16:12:54

标签: python string python-3.x if-statement

我有以下代码:

Info.AB

即使单词变量为空,它也会打印word = "" if (letter=="a" for letter in word): print("a found!") 。为什么会这样呢?而做我想做的正确方法是什么?

5 个答案:

答案 0 :(得分:2)

您在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!')

答案 1 :(得分:2)

之所以会这样,是因为语句(letter=="a" for letter in word) generator 。您的if语句检查该生成器是否是一个“真实的”对象(为了方便起见,python中的许多东西都评估为true-非空列表,非空字符串等),然后打印"a found!",因为该生成器求值为True

相反,您可能想要类似以下的内容。

word = ""
letter = "a"
if letter in word:
    print(f"{letter} found!")

答案 2 :(得分:0)

(letter=="a" for letter in word)返回一个生成器。由于生成器似乎既没有__len__也没有__bool__,因此它始终被评估为true。

您想要的代码就是这个:

word = ""
if ("a" in word):
  print("a found!")

答案 3 :(得分:0)

实际上,您可以使用

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()获得结果。

答案 4 :(得分:0)

以前的答案解释了为什么它不起作用,这只是一种使用列表理解来解决问题的方法:

word = "StackOverflow"
[print(letter + " found in:", word) for letter in word if letter == "a"]

哪个返回:

a found in: StackOverflow