Python 从指定范围内的整数中获取 N 个不同的数,有什么好的办法吗?

2019-04-09 15:26:19 +08:00
 coolair

比如:从 1-100 中随机获取 5 个不同的数。

def test(start, end, length):
    result = []
    while len(result) < length:
        number = randint(start, end)
        if number not in result:
            result.append(number)
    return result

我是这么写的,但是感觉不是很简洁,有更好的办法吗?

1831 次点击
所在节点    问与答
5 条回复
yzongyue
2019-04-09 15:55:55 +08:00
so 搜 random n number python
huahuajun9527
2019-04-09 16:04:30 +08:00
```python
import random

random.sample(range(1, 101), k=5)
```

https://docs.python.org/3/library/random.html#random.sample
ipwx
2019-04-09 16:22:46 +08:00
使用 random shuffle 算法,但不做完,只做前 k 项。取前 k 项即可。

https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle
ipwx
2019-04-09 16:28:59 +08:00
fngtz
2019-04-09 16:32:52 +08:00
我觉得很简洁。比 random.sample 简洁多了。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/553378

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX