从两个for循环中获取x,y值python

时间:2018-12-31 15:12:16

标签: python

我正在尝试从两个for循环中追加数字,以创建一些元组并将其添加到列表中。

li = []
for x in range(1,10):
    for y in range(1,10):
        li.append((x,y*2))
print(li)

我明白了

[(1, 2), (1, 4), (1, 6), (1, 8), (1, 10), (1, 12), (1, 14), (1, 16), (1, 18), (2, 2), (2, 4), (2, 6), (2, 8), (2, 10), (2, 12), (2, 14), (2, 16), (2, 18), (3, 2), (3, 4), (3, 6), (3, 8), (3, 10), (3, 12), (3, 14), (3, 16), (3, 18), (4, 2), (4, 4), (4, 6), (4, 8), (4, 10), (4, 12), (4, 14), (4, 16), (4, 18), (5, 2), (5, 4), (5, 6), (5, 8), (5, 10), (5, 12), (5, 14), (5, 16), (5, 18), (6, 2), (6, 4), (6, 6), (6, 8), (6, 10), (6, 12), (6, 14), (6, 16), (6, 18), (7, 2), (7, 4), (7, 6), (7, 8), (7, 10), (7, 12), (7, 14), (7, 16), (7, 18), (8, 2), (8, 4), (8, 6), (8, 8), (8, 10), (8, 12), (8, 14), (8, 16), (8, 18), (9, 2), (9, 4), (9, 6), (9, 8), (9, 10), (9, 12), (9, 14), (9, 16), (9, 18)]

但是,每个y只能是一个x。我该如何解决?

2 个答案:

答案 0 :(得分:5)

使用列表理解:

>>> [(x, x**2) for x in range(1, 10)]
[(1, 1), (2, 4), (3, 9), (4, 16), (5, 25), (6, 36), (7, 49), (8, 64), (9, 81)]

使用for循环:

>>> li = []
>>> for x in range(1, 10):
...     li.append((x, x**2))
... 
>>> li
[(1, 1), (2, 4), (3, 9), (4, 16), (5, 25), (6, 36), (7, 49), (8, 64), (9, 81)]

答案 1 :(得分:1)

如果使用第三方库作为NumPy没问题,还可以执行以下操作,避免任何显式的for循环。

P.S:对于您的小例子来说,这可能是一个矫but过正的做法,但了解替代方法还是很好的。

这里的zip根据输入的可迭代对象返回一个元组的迭代器。

import numpy as np
x = np.arange(1, 10)
print (list(zip(x, x**2)))

# [(1, 1), (2, 4), (3, 9), (4, 16), (5, 25), (6, 36), (7, 49), (8, 64), (9, 81)]