简体   繁体   中英

confusing behavior of tuple unpacking — for loop on a list of tuples

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]))]

For simplicity's sake, this list here only has 5 tuples.

When I run the following code, it seem I am able to unpack each tuple with each iteration:

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)

I'm confused as to how tuples are being unpacked in the earlier cases, that are preventing the last case to also successfully unpack the tuples.

Thank you.

In the first two cases you're looping through list , in the last one you're accessing tuple

Not sure what you want to achieve, but instead of data[0] , data[:1] would work.

If your data looks like this:

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

Output:

[2, 1, 3] [1]
[2, 1, 2] [1]
[4, 4, 4] [0]
[4, 1, 1] [0]
[4, 4, 3] [0]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM