Python 从列表中选择 20 个随机结果

Tho*_*hom -1 python random

我想从以下列表中获得 20 个随机结果:

coordinates = [
  [20, 140], [40, 140], [60, 140], [80, 140], [100, 140], [120, 140],
  [20, 120], [40, 120], [60, 120], [80, 120], [100, 120], [120, 120],
  [20, 100], [40, 100], [60, 100], [80, 100], [100, 100], [120, 100],
  [20, 80], [40, 80], [60, 80], [80, 80], [100, 80], [120, 80],
  [20, 60], [40, 60], [60, 60], [80, 60], [100, 60], [120, 60],
  [20, 40], [40, 40], [60, 40], [80, 40], [100, 40], [120, 40]
]
Run Code Online (Sandbox Code Playgroud)

我试过了,random.shuffle但它返回None

Wil*_*ill 10

如果您想要随机顺序的20 个唯一值,请使用random.sample()

random.sample(coordinates, 20)
Run Code Online (Sandbox Code Playgroud)
random.sample(population, k)¶
Run Code Online (Sandbox Code Playgroud)

返回从总体序列或集合中选择的唯一元素的k长度列表。用于不放回的随机抽样。

>>> random.sample(coordinates, 20)
[[80, 60], [40, 100], [80, 100], [60, 80], [60, 100], [40, 60], [40, 80], [80, 120], [120, 140], [120, 100], [100, 80], [40, 120], [80, 140], [100, 140], [20, 80], [120, 80], [100, 100], [20, 40], [120, 120], [100, 120]]
Run Code Online (Sandbox Code Playgroud)

您可以使用random.choice()20 次,但这不会是“唯一的”——元素可能会重复,因为每次都会随机选择一个:

>>> [random.choice(coordinates) for _ in range(20)]
[[80, 80], [40, 140], [80, 140], [60, 60], [120, 100], [20, 120], [100, 80], [120, 100], [20, 60], [100, 120], [100, 40], [80, 80], [100, 80], [80, 120], [20, 40], [100, 80], [60, 80], [80, 140], [40, 40], [120, 40]]
Run Code Online (Sandbox Code Playgroud)


Leu*_*noe 6

random.sample我想你可能正在图书馆寻找random。你可以这样使用:

import random
my_new_list = random.sample(coordinates, 20)
Run Code Online (Sandbox Code Playgroud)