2013-04-08 32 views

回答

2

您可以zip()它們合併:

zip(x, y) 

,或者你可以生成數字一起入手:

[(random.randint(0,100), random.randint(0,100)) for i in xrange(3000)] 
0

您可以使用zip

>>> x = [(random.randint(0,100)) for i in range(3000)] 
>>> y = [(random.randint(0,100)) for j in range(3000)] 
>>> coords = zip(x,y) 
>>> len(coords) 
3000 
>>> type(coords[0]) 
<type 'tuple'> 
>>> coords[0] 
(54, 0) 
>>> 
0

您可以在列表中的元組添加到包含座標的新名單:

import random 
import pylab 

XY=[] 

x = [(random.randint(0,100)) for i in range(3000)] 
y = [(random.randint(0,100)) for j in range(3000)] 

for xg, yg in zip(x,y): 
    XY.append((xg,yg)) 
+0

爲什麼循環遍歷'zip()'?在Python 2中,它已經是一個列表,並且你可以在Python 3的'zip()'結果中調用'list()'。 – 2013-04-08 15:24:30

+0

我不知道的好點! – 2013-04-08 15:26:03

1

我注意到你正在導入pylab。如果你很高興使用NumPy陣列爲座標,你可以簡單地寫:

import numpy.random 
coord = numpy.random.randint(0, 100, (3000, 2)) 

無需顯式循環或列表內涵。這使得代碼比純Python版本快120倍:

In [6]: %timeit coord = numpy.random.randint(0, 100, (3000, 2)) 
10000 loops, best of 3: 82.7 us per loop 

In [7]: %timeit coord = [(random.randint(0,100), random.randint(0,100)) for i in xrange(3000)] 
100 loops, best of 3: 10.3 ms per loop