简体   繁体   English

这种打印语法如何工作? print('something',['a','list'] [boolean])

[英]How does this print syntax work? print('something', ['a', 'list'][boolean])

print('something', ['a', 'list'][boolean])

Depending on the boolean value this either prints, a or list. 根据布尔值,这将打印,a或列表。

I have never seen this notation before and am wondering how it works. 我以前从未见过这种符号,我想知道它是如何工作的。

Notice the following in python 请注意python中的以下内容

>>> True == 1
True
>>> False == 0
True

as booleans are integers (in Python). 因为布尔整数(在Python中)。 so [0,1,2][False] == 0 and [0,1,2][True] == 1 所以[0,1,2][False] == 0[0,1,2][True] == 1

  1. Python's bool is a subclass of int , where True is 1 and False is 0. Python的boolint的子类,其中True为1, False为0。
    isinstance(True, int) # True
  2. As such, booleans can be used as indexes. 因此,布尔值可以用作索引。 ['a', 'list'][boolean] evaluates to ['a', 'list'][boolean]计算结果为
    ['a', 'list'][0] if boolean is False or to ['a', 'list'][1] if boolean is True ['a', 'list'][0]如果boolean值为False或者['a', 'list'][1]如果boolean值为True

This can be abused by using conditions directly: 这可以通过直接使用条件来滥用:

x = 1
print(['no', 'yes'][x > 0])
# yes

The boolean is either True or False . 布尔值为TrueFalse If you have a list mylist then mylist[0] gets you the first element and mylist[1] gets you the second element. 如果你有一个列表mylist那么mylist[0]会获得第一个元素,而mylist[1]会获得第二个元素。 mylist[False] means the same as mylist[0] . mylist[False]表示与mylist[0]相同。 Now suppose mylist contains ["list", "a"] . 现在假设mylist包含["list", "a"] Then ["list", "a"][False] will give you the same value as mylist[0] which is "list" . 那么["list", "a"][False]会给你与mylist[0]相同的值,即"list"

You are accustomed to seeing index notation (for example [0] ) after the name of a list, as in mylist[0] . 您习惯于在列表名称后面看到索引表示法(例如[0] ),如在mylist[0] But it can just as well be used after a list literal, as in ["list", "a"][0] . 但它也可以在列表文字之后使用,如["list", "a"][0]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM