Generate a large list of points with no duplicates

前端 未结 4 1268
悲&欢浪女
悲&欢浪女 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
    

提交回复
热议问题