質問

I started learning python few weeks ago(with no previous knowledge in programming), and went onto the following problem related to unpacking of sequences, which confuses me a lot.

For some reason when I try this:

for b, c in [1,2]:
    print b,c

I am getting an error message:

TypeError: 'int' object is not iterable

The same happens when I try to replace the list with a tuple (1,2)

But when I try the same thing, just with a tuple inside of list:

for b, c in [(1,2)]:
    print b,c

it works - I get:

1 2

Why is that?

Thank you.

btw I am using Python 2.7

役に立ちましたか?

解決

Everytime you do a in <iterable> statement, it fetches one item from the iterable and then unpacks it according to your needs, in your case b, c. So, in the first example, you try to assign b, c to 1 which is not possible, whereas in next example you do b, c = (1, 2) which unpacks successfully and gives you a b, c.

For example, try to print out the values.

>>> for x in [1, 2]:
        print "X: ", x


X:  1
X:  2

>>> for x in [(1, 2)]:
        print "X: ", x


X:  (1, 2)

So, assigning b, c = 1 is not possible, whereas assigning b, c = (1, 2) is possible.

他のヒント

In Python, a for loop takes each item from the iterable, and assigns it to the given name(s), before executing the code block each time.

In the first case, Python takes the first item, 1 and tries to assign it to b, c - this doesn't work as there is only one value to assign, hence the error.

In the second example, the first value is the entire tuple (1, 2) - so this can be unpacked, as it contains the two required values.

It's clear what the issue is when you put it into context:

a, b = 1, 2
a, b = 1

One value can't become two.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top