迄今爲止,已創建了2個分別標記爲x和y的數據點列表。我不知道如何將它們組合成一個單一的數組,雖然它們是座標。在這樣的陣列內生成數千個隨機位置的陣列,例如(3,75)和(56,34)
import random
import pylab
x = [(random.randint(0,100)) for i in range(3000)]
y = [(random.randint(0,100)) for j in range(3000)]
迄今爲止,已創建了2個分別標記爲x和y的數據點列表。我不知道如何將它們組合成一個單一的數組,雖然它們是座標。在這樣的陣列內生成數千個隨機位置的陣列,例如(3,75)和(56,34)
import random
import pylab
x = [(random.randint(0,100)) for i in range(3000)]
y = [(random.randint(0,100)) for j in range(3000)]
您可以zip()
它們合併:
zip(x, y)
,或者你可以生成數字一起入手:
[(random.randint(0,100), random.randint(0,100)) for i in xrange(3000)]
您可以使用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)
>>>
您可以在列表中的元組添加到包含座標的新名單:
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))
我注意到你正在導入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
爲什麼循環遍歷'zip()'?在Python 2中,它已經是一個列表,並且你可以在Python 3的'zip()'結果中調用'list()'。 – 2013-04-08 15:24:30
我不知道的好點! – 2013-04-08 15:26:03