Generate a large list of points with no duplicates

孤街醉人 提交于 2019-11-28 11:31:04

问题


I want to create a large list containing 20,000 points in the form of:

[[x, y], [x, y], [x, y]]

where x and y can be any random integer between 0 and 1000. How would I be able to do this such that there are no duplicate coordinates [x, y]?


回答1:


You could just use a while loop to pad it out until it's big enough:

>>> from random import randint
>>> n, N = 1000, 20000
>>> points = {(randint(0, n), randint(0, n)) for i in xrange(N)}
>>> while len(points) < N:
...     points |= {(randint(0, n), randint(0, n))}
...     
>>> points = list(list(x) for x in points)

Your initial idea was probably slow because it was iterating lists for checking containmentship, which is O(n). This uses sets which are faster, and then only converts to the list structure once at the end.




回答2:


Try this :

import itertools
x = range(0,10)
aList =[]
for pair in itertools.combinations(x,2):
    for i in range(0,10):
        aList.append(pair)
print aList

If you want point between 0-10 with all unique and stored in a list, or you You need it random order, then use some random function .




回答3:


Since n = 1001 is relatively small in your case, random.sample(population, k) will do just fine, taking a random sample of 20000 pairs from the space of possible pairs (no duplicates):

import random
print random.sample([[x, y] for x in xrange(1001) for y in xrange(1001)], 20000)

This is the most concise and readable solution. (But if n is very big, generating the entire space of points will not be computationally efficient.)




回答4:


An approach that avoids while loops with unknown iteration counts and avoids storing huge lists in memory is to use random.sample to produce unique encoded values from a single range (in Py3) or xrange (in Py2) to avoid actually generating huge temporaries; a simple mathematical operation can split the "encoded" values back into two values:

import random
xys = random.sample(range(1001 * 1001), 20000)
[divmod(xy, 1001) for xy in xys] # Wrap divmod in list() if you must have list, not tuple


来源:https://stackoverflow.com/questions/30610885/generate-a-large-list-of-points-with-no-duplicates

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!