既然元组在 Python 中是不可变的数据类型,而元组推导式不是一回事,那么为什么使用圆括号而不是方括号的列表推导式可以正常工作并生成常规元组?
我认为圆括号用于定义元组而不是列表(我知道我没有错)。
根据我的理解,我将值附加到已经定义的元组,并且我能够更新元组,这不应该发生(在 Python 中),因为元组是不可变的。
我没有收到任何错误,有人请告诉我对此有合理的解释。
这是我的代码:
ignore = (r"^\@define\s")
x = tuple()
(x.append(True if re.search(regex, line) else False) for regex in ignore)
if True in x:
print("How is this possible?")
最佳答案
没有抛出错误,因为您使用的是生成器表达式。
>>> x = tuple()
>>> x
()
>>> (x.append(i) for i in range(10))
<generator object <genexpr> at 0x110bede60>
生成器是惰性求值的,因为你甚至没有在变量中捕获生成器,它只是被垃圾收集。但是,看看当我确实使用生成器时会发生什么:
>>> g = (x.append(i) for i in range(10))
>>> next(g)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <genexpr>
AttributeError: 'tuple' object has no attribute 'append'
生成器 是一种快速、酷炫的编写迭代器的方法。 generator 表达式本质上是“生成器的列表理解”,但您可以使用 yield
编写生成器:
>>> def my_generator():
... yield 1
... yield 3
...
>>> g = my_generator()
>>> next(g)
1
>>> next(g)
3
>>> next(g)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
>>> list(my_generator())
[1, 3]
>>>
现在,生成器表达式的妙处在于您可以将它们与 tuple
构造函数结合使用,它接受任何可迭代对象,并且您对元组的理解有点像穷人! *注意,如果只有一个参数,您可以将括号放在函数参数中:
>>> tuple(x for x in range(20))
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19)
>>>
顺便说一句,你不应该永远运行这样的代码:
>>> x = []
>>> [x.append(i) for i in range(10)]
[None, None, None, None, None, None, None, None, None, None]
>>> x
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
首先,它很浪费,因为它创建了一个完全无用的 None
列表。其次,它混合了功能构造、列表理解和状态更改 (.append
),这是一种糟糕的形式。 Python 程序员希望列表理解不会那样做。 只需对命令式代码使用 for 循环。
关于python - 为什么当我将新元素附加到 TUPLE 时它会起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41708806/