gpt4 book ai didi

python - 在Python for循环中使用 "or"来定义默认序列

转载 作者:行者123 更新时间:2023-11-30 23:08:34 24 4
gpt4 key购买 nike

我在某处看到过 for 循环的这种用法:

def func(seq=None):
for i in seq or [1, 2, 3]:
print i

func([3, 4, 5]) # Will print 3, 4, 5
func() # Will print 1, 2, 3

似乎当使用 or/and 使用“in”关键字时,它将选择第一个/最后一个“可用”序列以运行 for 循环。

我没有看到任何官方文档,想知道它是如何工作的以及它是否常用。

最佳答案

如果是 or (或 and )运算符,当您执行 -

a or b

如果 a 不是类似 false 的值,则返回 a ,否则返回 bNone(和空列表)与值一样都是 false。

来自documentation -

The expression x and y first evaluates x; if x is false, its value is returned; otherwise, y is evaluated and the resulting value is returned.

The expression x or y first evaluates x; if x is true, its value is returned; otherwise, y is evaluated and the resulting value is returned.

(Note that neither and nor or restrict the value and type they return to False and True, but rather return the last evaluated argument. This is sometimes useful, e.g., if s is a string that should be replaced by a default value if it is empty, the expression s or 'foo' yields the desired value. Because not has to invent a value anyway, it does not bother to return a value of the same type as its argument, so e.g., not 'foo' yields False, not ''.)

<小时/>

此外,在 for 循环的情况下,in 实际上是 for 循环构造的一部分,而不是运算符。 for 循环构造的文档 here .

<小时/>

因此,当你这样做时 -

for i in seq or [1, 2, 3]:

它首先会评估 -

seq or [1 , 2, 3]

如果 seq 列表不为空或为空,则返回该列表,以便您可以对其进行迭代。否则,它将返回 [1, 2, 3] 并且您将对其进行迭代。

关于python - 在Python for循环中使用 "or"来定义默认序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31636978/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com