使用“或”在python for循环中定义默认序列 [英] Using "or" in a python for loop to define default sequence
问题描述
def func(seq = None):
对于我在seq或[1,2,3]:
打印我
func([3,4,5])将打印3,4,5
func ()#将打印1,2,3
看来,当使用或/和当使用in关键字会选择第一个/最后一个可用的顺序来运行for循环。
我还没有看到任何官方文档,想知道它是如何如果它是常用的。
如果或
(或和
)运营商,当你这样做 -
a或b
如果a不是false,则返回 a
类似的值,否则返回 b
。 没有
(和空列表)是假的像价值
从 documentation -
表达式
x和y
首先计算x
;如果x
为false,则返回其值;否则,将评估y
并返回结果值。
表达式
x或y
首先评估x
;如果x
为true,则返回其值;否则,计算y
并返回结果值。
(注意,既不和也不限制值如果
s
是一个应该被默认值替换的字符串,则返回False和True,而是返回最后一个被评估的参数。如果它是空的,表达式s或'foo'
就会产生所需的值,因为不必发明一个值,所以不用麻烦返回相同的值键入作为它的参数,例如,不是'foo'产生False,而不是''。
另外,如果 for
循环,中的
实际上是
对于
循环结构,它不是一个运算符。 的文档
循环结构此处。
因此当你这样做时 -
<$对于我在seq或[1,2,3]:
它会首先评估 -
seq或[1,2,3]
返回 seq
列表,如果它不为空或者为空,以便迭代那。否则,它会返回[1,2,3],你会迭代。
I have seen somewhere this usage of a for loop:
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
It seems that when using or/and when using the "in" keyword it will select the first/last "usable" sequence in order to run the for loop.
I have not seen any official documentation and was wondering how it works and if it's commonly used.
In case of or
(or and
) operator, when you do -
a or b
It returns a
if a is not a false-like value, otherwise it returns b
. None
(and empty lists) are false like value.
From documentation -
The expression
x and y
first evaluatesx
; ifx
is false, its value is returned; otherwise,y
is evaluated and the resulting value is returned.The expression
x or y
first evaluatesx
; ifx
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 expressions 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 ''.)
Also, in case of for
loop, in
is actually part of the for
loop construct, its not an operator. Documentation for for
loop construct here.
Hence when you do -
for i in seq or [1, 2, 3]:
It would first evaluate -
seq or [1 , 2, 3]
And returns the seq
list if its not none or empty, so that you can iterate over that. Otherwise, it would return [1, 2, 3] and you would iterate over that.
这篇关于使用“或”在python for循环中定义默认序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!