生成大量的点,没有重复的点 [英] Generate a large list of points with no duplicates

查看:58
本文介绍了生成大量的点,没有重复的点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个包含20,000点的大列表,形式为:

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

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

其中x和y可以是0到1000之间的任何随机整数.我如何能够做到没有重复的坐标[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]?

推荐答案

您可以使用while循环将其填充,直到足够大为止:

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)

您最初的想法可能很慢,因为它正在迭代用于检查遏制性的列表,即 O(n).这将使用速度更快的集合,然后最后只转换一次为列表结构.

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.

这篇关于生成大量的点,没有重复的点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆