奇怪的 python 语法,或者在 print 语句中

Strange python syntax, or in print statement

我找不到这方面的任何信息,所以我不得不在这里问。我敢肯定,对于任何了解 python 的人来说,这都是一个简单的问题。

python 2:

print raw_input() == 0 or hash(tuple(map(int, raw_input().split(' '))))

python 3:

print(input()==0 or hash(tuple(map(int,input().strip().split()))))

我想了解为什么 'or' 出现在打印语句中。 有问题的代码在 print 语句中有一个布尔运算符,用于比较布尔值和 int。这就是我需要向我解释的。它显然是 python 特有的。如果 input()==0 returns 为真,代码会打印什么?我们如何比较布尔值和散列值,再一次,我们在 print 语句中进行布尔值比较是做什么的?

Python会先判断input()==0是否为True。如果是,那么 Python 将打印它并忽略该行的其余部分。如果输入不等于 0 并且其计算结果为 False,那么它将被忽略并且该行的其余部分将被打印 ,无论它如何计算。因此,即使该行的其余部分的计算结果为 False,Python 也会打印其结果。

一个更清晰的例子是根据用户输入设置某物的名称并需要一个默认值。

name = raw_input("What is your name?")
print ("So your name is...")
print (name or "John Smith")

name 将计算为 TrueFalse。由于空字符串将被视为 False,如果用户未输入任何内容,则 Python 将在 or 运算符后打印默认名称。

在 Python 中,与 orand 的比较利用了两个特征:

  1. Truthy and falsey values,以及
  2. Short-circuiting.

所以,当你遇到这样的事情时:

print(input()==0 or hash(tuple(map(int,input().strip().split()))))

它会按照操作的顺序,检查input() return是否是0。因为是 or 下一项,如果为真那么下一项对结果没有影响,不会被评估。如果发生这种情况,它将打印 True,因为那是 input()==0 编辑的 return。

如果为假,它将评估下一部分,获取输入,将其映射为整数,将其转换为元组,然后对其进行哈希处理。然后它将 return 散列它是否为真值([=14= 以外的数字]、序列或包含内容的集合等)。

我猜你的代码是 Python3,否则 input() 的结果不太可能有 strip 方法。

这里是一个长格式的代码,附有解释。

# Read a line of input. Returns a string.
a = input()
# Compare to integer 0, always False.
# Effectively, this ignores the first line of input.
b = a == 0
# Separate function to represent lazy evaluation.
def y():
    # Get a second line of input, as a string.
    c = input()
    # Strip leading and trailing whitespace, still a string.
    # This line is useless since split() with no argument does this.
    d = c.strip()
    # Split the line by any runs of whitespace. Returns a list of strings.
    e = d.split()
    # For each string in the list, convert it to an integer in base 10.
    # Return an iterator (not list) of ints.
    # Most people would write (int(s) for x in e) for a generator
    # comprehension, or [int(s) for x in e] for a list comprehension.
    m = map(int, e)
    # Consume the iterator into a tuple of ints.
    # Note that it can't be a list, because lists aren't hashable.
    t = tuple(m)
    # Hash the tuple, returning a single int.
    return hash(t)
# If b is truthy, set x to it. Otherwise, evaluate y() and set x to that.
# Unlike many languages, the arguments to or are *not* coerced to bool.
# Since b is False, y() will be evaluated.
x = b or y()
# Print the result of y().
# i.e. the hash of the tuple of ints on the second line.
# This is essentially a meaningless number.
print(x)