gpt4 book ai didi

python - "too many values to unpack (expected 2)"数组元素len大于2时

转载 作者:行者123 更新时间:2023-12-04 01:22:51 24 4
gpt4 key购买 nike

也许问这个问题会很奇怪,因为我当然不明白。

例如,如果我们有 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 是一个 listtuples .所以 a[0](1,2)a[1](3,4)

因此,如果您向其中一个元组添加更多元素,您实际上并没有改变a。因为,请记住,a 只是元组。您正在更改元组中的值。因此,a 的长度永远不会改变。

如果你想访问所述元组的值,你可以这样做print(a[0][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:\Users\Kelly\wundermahn\example.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

关于python - "too many values to unpack (expected 2)"数组元素len大于2时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62361495/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com