python for循环问题,很困扰
黄舟
黄舟 2017-04-18 10:31:51
0
2
500
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。
不然得怎么理解?

黄舟
黄舟

人生最曼妙的风景,竟是内心的淡定与从容!

reply all(2)
PHPzhong

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.

黄舟

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//不确定
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!