Generate a large list of points with no duplicates

前端 未结 4 1243
悲&欢浪女
悲&欢浪女 2020-12-21 21:49

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 bet

相关标签:
4条回答
  • 2020-12-21 22:45

    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
    
    0 讨论(0)
  • 2020-12-21 22:48

    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 .

    0 讨论(0)
  • 2020-12-21 22:49

    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.

    0 讨论(0)
  • 2020-12-21 22:51

    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.)

    0 讨论(0)
提交回复
热议问题