Onilol Onilol - 1 year ago 72
Python Question

Swapping range of random elements in lists with list comprehension

I have to pick a N number of elements from a list randomly, remove them from the list and add them to another one. My approach so far is something like this:

import random

x = ['a','b','c','d','e','f','g']
y = []
for v in reversed(list(x)):
z = x.pop(x.index(random.choice(x)))

which outputs:

['a', 'b', 'c', 'd', 'e', 'f', 'g']
['a', 'b', 'c', 'd', 'f', 'g']
['a', 'b', 'c', 'd', 'g']
['b', 'c', 'd', 'g']
['b', 'c', 'g']
['c', 'g']
['e', 'f', 'a', 'd', 'b', 'c', 'g']

is there a way to write this using list comprehensions? It's going beyond my comprehension.

The original list does not end shuffled, it just has the choosen elements removed.

Answer Source
y = [x.pop(random.randrange(len(x))) for _ in range(len(x))]

If you really want to do exactly this, yes. There are better ways though.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download