Thom - 1 year ago 89
Python Question

# Python pick 20 random results from list

I would like to get 20 random results from the following list

``````coordinaten = [[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]]
``````

I tried random.shuffle but it returns me an empty list.

I hope someone can help me out.

EDIT:

Got it working, didn't know you could give an parameter to random.shuffle()
Thanks for your replies.

Answer Source

You could use `random.choice()` 20 times, but this will not be "unique"--elements may be duplicated, because one is randomly selected each time:

``````[random.choice(coordinaten) for _ in xrange(20)]
``````

If you want 20 unique values in random order, use `random.sample()`:

``````random.sample(coordinaten, 20)
``````
``````random.sample(population, k)ΒΆ

Return a k length list of unique elements chosen from the population
sequence. Used for random sampling without replacement.
``````

New in version 2.3.

See here:

``````In [14]: print random.sample(coordinaten, 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]]

In [15]: print [random.choice(coordinaten) for _ in xrange(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]]
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download