Discuss / Python / x,y有何作用?

x,y有何作用?

Topic source

iter complex list:

print('iter [(1, 1), (2, 4), (3, 9)]:') for x, y in [(1, 1), (2, 4), (3, 9)]: print(x, y)

直接用: for x in [(1, 1), (2, 4), (3, 9)]: print(x) 也可以。

那第一种方法用x,y有何作用?

Cod1ng

#2 Created at ... [Delete] [Delete and Lock User]

第二种方法取出的是元组,而第一种方法可以把元祖里面的几个值给取出来

廖雪峰

#3 Created at ... [Delete] [Delete and Lock User]

正常情况下你这么写:

for t in [(1, 1), (2, 4), (3, 9)]:
    x = t[0]
    y = t[1]
    print(x + y)

现在改成这样代码不是更少吗?

for x, y in [(1, 1), (2, 4), (3, 9)]:
    print(x + y)

  • 1

Reply