Python 解压与显式循环

Python 解压与显式循环,python,Python,解压两个压缩列表的两种方法有什么不同 assert isinstance(X, list) assert isinstance(X[0], tuple) assert isinstance(X[0][0], list) assert isinstance(X[0][0][0], dict) X_model = [] X_synth = [] for row in X: X_model.append(row[0]) X_synth.append(row[1]) X_模型现在是d

解压两个压缩列表的两种方法有什么不同

assert isinstance(X, list)
assert isinstance(X[0], tuple)
assert isinstance(X[0][0], list)
assert isinstance(X[0][0][0], dict)

X_model = []
X_synth = []
for row in X:
    X_model.append(row[0])
    X_synth.append(row[1])
X_模型现在是dict列表

X_model, X_synth, = zip(*X)
X_模型是一个dict列表的元组
结果不应该相同吗?

让我们举个例子。为了简单起见,让我们使用数字,而不是使用dicts列表。请注意,每个元组的第一个元素是奇数,而每个元组的第二个元素是偶数

>>> X = [(1, 2), (3, 4), (5, 6), (7, 8), (9, 10)]
>>> X_model = []
>>> X_synth = []
>>> for row in X:
...     X_model.append(row[0])
...     X_synth.append(row[1])
...
>>> X_model
[1, 3, 5, 7, 9]
>>> X_synth
[2, 4, 6, 8, 10]
>>> X_model, X_synth = zip(*X)
>>> X_model
(1, 3, 5, 7, 9)
>>> X_synth
(2, 4, 6, 8, 10)

让我们考虑<代码> zip(*x)< /代码>。code>zip(*X)相当于

zip((1, 2), (3, 4), (5, 6), (7, 8), (9, 10))

邮编: 此函数返回元组列表,其中第i个元组包含每个参数序列或iterables中的第i个元素

因此,zip将返回一个元组列表,其中第0个元组包含每个参数的第0个元素(所有奇数),第1个元组包含每个参数的所有第一个元素(所有偶数)


zip()
等效的是:

X_model = tuple(x for x, _ in X)
X_synth = tuple(x for _, x in X)
但这不是很有效,因为它循环
X
两次。 注意:
tuple
s是不可变的,因此不能在循环中高效地执行,因为每次都会创建一个新的tuple

X_model = tuple(x for x, _ in X)
X_synth = tuple(x for _, x in X)