也许问这个问题会很奇怪,因为我当然不明白。
例如,如果我们有a=[(1,2), (3,4)]
; 操作有效
for x,y in a:
print(x,y)
但是一旦我们向这些元组添加任何其他元素,a=[(1,2,3),(4,5,6)]
for x,y in a:
print(x,y)
---------------
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: too many values to unpack (expected 2)
但是使用zip(a[0],a[1])
工作是有效的
我看到这个问题以前被问过很多次,但我找不到任何关于为什么超过 2 的 len 不起作用的问题。
谁能向我解释为什么会这样?
好问题。
在a=[(1,2), (3,4)]
的情况下,了解这些数据结构是什么是很重要的。
a
是元组的列表。所以a[0]
是(1,2)
,a[1]
是(3,4)
因此,如果您向其中一个元组添加更多元素,则实际上不会更改a
。因为,请记住,a
只是元组。您正在更改元组中的值。因此,a
的长度永远不会改变。
如果你想访问所述元组的值,你可以这样做 产生0
print(a[0][0])
一个示例程序来理解我的意思:
a = [(1,2), (3,4)]
b = [(1,2,3), (4,5,6)]
def understand_data(x):
print("First, let's loop through the first structure and see what it is")
print("You passed in: {}".format(type(x)))
print("Now printing type and contents of the passed in object")
for i in range(len(x)):
print(type(x[i]))
print(x[i])
print("Now printing the contents of the contents of the passed in object")
for i in range(len(x)):
for j in range(len(x[i])):
print(x[i][j])
print("DONE!")
understand_data(a)
understand_data(b)
收益 率:
[Running] python -u "c:UsersKellywundermahnexample.py"
First, let's loop through the first structure and see what it is
You passed in: <class 'list'>
Now printing type and contents of the passed in object
<class 'tuple'>
(1, 2)
<class 'tuple'>
(3, 4)
Now printing the contents of the contents of the passed in object
1
2
3
4
DONE!
First, let's loop through the first structure and see what it is
You passed in: <class 'list'>
Now printing type and contents of the passed in object
<class 'tuple'>
(1, 2, 3)
<class 'tuple'>
(4, 5, 6)
Now printing the contents of the contents of the passed in object
1
2
3
4
5
6
DONE!
[Done] exited with code=0 in 0.054 seconds
抛出too many values to unpack
,因为您正在尝试将 3 个元素的元组解压缩(分配给变量(为 2 个变量 -x
和y
.
如果您的元组由n
元素组成,则应使用n
变量解压缩它们,因此在您的情况下:
for x,y,z in a:
pass
zip(a[0],a[1])
之所以适合您,是因为zip
在您的示例中创建了一个包含 2 个元素元组的迭代器。例如,如果您将其更改为zip(a[0],a[1], a[2])
,它将不起作用,因为将创建 3 个元素元组的迭代器,而 2 个变量不足以解压缩它。
首先,尝试:
a = [(1, 2, 3), (4, 5, 6)]
for i in a:
x, y, z = i
print(x, y, z)
它应该返回:
1 2 3
4 5 6
变量 x 扮演托运人,他将 3 个箱子从仓库a带到 3 个不同的客户x、y、y中。接下来,如果托运人辞职,那么3个人需要自己去仓库。所以,我们有一个变化:
a = [(1, 2, 3), (4, 5, 6)]
for x, y, z in a:
print(x, y, z)
它返回与上述相同的结果。
奖金,如果只有 2 个客户收到 3 盒。X得到一个盒子,y得到两个剩余的盒子。
a = [(1, 2, 3), (4, 5, 6)]
for x, *y in a:
print(x, y)
输出:
1 [2, 3]
4 [5, 6]
希望有用!
因为a
中的元组每个有三个元素,所以你需要三个变量来解压缩它们。 那是
for x,y,z in a:
...
您的zip
示例之所以有效,是因为zip
从可迭代对象的各个元素(在本例中为元组(创建一个元组。 只有两个迭代对象传递给zip
(即a[0]
和a[1]
(。 这就是为什么您只需要两个变量来解压缩它们的原因。
为了更好地了解这一点,请尝试运行以下代码:
for x in a:
print(x)
您将看到需要三个变量来表示x
的各个值。
然后看一下输出:
for x in zip(a[0],a[1]):
print(x)