Home  >  Q&A  >  body text

python for循环问题,很困扰

a=['one','two']
for p,q in a:
    print p,q

出错

a=[['one','tow']]
for p,q in a:
    print p,q

这样就可以
第一种我一直就认为是这样的:a的one,two分别赋值给p,q。
不然得怎么理解?

黄舟黄舟2741 days ago496

reply all(2)I'll reply

  • PHPz

    PHPz2017-04-18 10:33:51

    In Python, a for loop runs through each element in a list (or generator). So the correct form of the first loop is:

    for x in a:
        print(x)

    In addition, in Python we can write:

    x, y = (1, 2)

    From now on, x is 1 and y is 2. We can also write:

    x, y = [1, 2]

    Has the same effect.
    If we write: x, y = 1There is an error, except for the exact same error in one of your for loops.

    In the second f example the list [['one', 'two']]只有个元素,就是['one', 'two']。for循环要跑一次,这一次p, q就是['one', 'two'] is similar to the example above.

    reply
    0
  • 黄舟

    黄舟2017-04-18 10:33:51

    In the first example, a has two elements, namely 'one', 'two'. The assignment is uncertain on p and q.
    In the second example, a has an element ['one', 'two' '], the order is determined.

    p, q = [x, y] //可行
    p, q = x, y//不确定
    

    reply
    0
  • Cancelreply