I have a list of tuples `data`:
data =[(array([[2, 1, 3]]), array([1])),
(array([[2, 1, 2]]), array([1])),
(array([[4, 4, 4]]), array([0])),
(array([[4, 1, 1]]), array([0])),
(array([[4, 4, 3]]), array([0]))]
为简单起见,此列表中只有5个元组。
当我运行以下代码时,似乎我能够解压缩每个元组 每次迭代:
for x,y in data2:
print(x,y)
output:
[[2 1 3]] [1]
[[2 1 2]] [1]
[[4 4 4]] [0]
[[4 1 1]] [0]
[[4 4 3]] [0]
This also works:
for x,y in data2[:2]:
print(x,y)
output:
[[2 1 3]] [1]
[[2 1 2]] [1]
However, when I take only a single tuple from the list:
for x,y in data2[0]:
print(x,y)
output:
ValueError Traceback (most recent call last)
<ipython-input-185-1eed1fccdb3a> in <module>()
----> 1 for x,y in data2[0]:
2 print(x,y)
ValueError: not enough values to unpack (expected 2, got 1)
我对在早期案例中如何解包元组感到困惑 防止最后一个案例也成功解压缩元组。
谢谢。
答案 0 :(得分:4)
在前两种情况下,您正在循环浏览list
,在您访问的最后一个tuple
不确定要实现的目标,但data[0]
代替data[:1]
,而不是{{1}}。
答案 1 :(得分:0)
如果您的数据如下所示:
data =[([[2, 1, 3]], [1]),
([[2, 1, 2]], [1]),
([[4, 4, 4]]), [0]),
([[4, 1, 1]], [0]),
([[4, 4, 3]], [0])]
for [a], b in data:
print a, b
输出:
[2, 1, 3] [1]
[2, 1, 2] [1]
[4, 4, 4] [0]
[4, 1, 1] [0]
[4, 4, 3] [0]