我使用了生成器表达式,然后使用了列表推导,'_'在这里做什么?
x = (i for i in [1, 2, 3])
[_ for i in x]
它给出了这样的输出
[]
[[], [], []]
[[[], [], []], [[], [], []], [[], [], []]]
[[[[], [], []], [[], [], []], [[], [], []]],
[[[], [], []], [[], [], []], [[], [], []]],
[[[], [], []], [[], [], []], [[], [], []]]]
多次运行两行
答案 0 :(得分:3)
如果您正在Python REPL上运行代码(我想是这样),那么下划线是一个内置变量,该变量保存上一次计算的值(在计算值时由REPL更新)。
例如:
>>> x = 5 # this is not _
>>> _ ** 2 # so referencing it will raise a NameError
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name '_' is not defined
>>> 5 # the result of this will be the value referenced by _
5
>>> _ ** 2 # now referencing it is okay
25
>>> _ ** 2 # note that now the value of _ is 25 (the last value calculated)
625
>>> # and here its value is 625 (and so on)