Generate a large list of points with no duplicates

2019-03-01 00:05发布

问题:

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