Reputation: 78
I have some lists:
original = [1234, 2456, 1245, 5734, 1245, 74512, 13678, 1456, 3926, 1974]
list1 = []
list2 = []
list3 = []
list4 = []
I'm trying to move a certain amount of numbers from the original list into the new lists. list1
should have 4, list2
should have 3, list3
should 2, and list4
should have 1. The numbers that go into the new lists should be picked randomly and not in any particular order. There also shouldn't be any of the same numbers in 2 lists; all lists should have unique numbers.
How should I solve this?
Upvotes: 0
Views: 877
Reputation: 71454
Here's one way, using random.randrange
and list.pop
(you said you want to "move" items from original
so I assume it's supposed to be empty when you're done -- if not you could do this with a copy):
>>> import random
>>> original = [1234, 2456, 1245, 5734, 1245, 74512, 13678, 1456, 3926, 1974]
>>> list1 = []
>>> list2 = []
>>> list3 = []
>>> list4 = []
>>> for i, target in enumerate([list4, list3, list2, list1]):
... for _ in range(i+1):
... target.append(original.pop(random.randrange(len(original))))
...
>>> [list1, list2, list3, list4]
[[3926, 1234, 1456, 74512], [13678, 2456, 1245], [5734, 1245], [1974]]
>>> original
[]
Note that any time you have a bunch of numbered variables (like list1
, list2
, etc) it's usually easier to just make them a list:
>>> original = [1234, 2456, 1245, 5734, 1245, 74512, 13678, 1456, 3926, 1974]
>>> sublists = [[] for _ in range(4)]
>>> for i, s in enumerate(reversed(sublists)):
... for _ in range(i+1):
... s.append(original.pop(random.randrange(len(original))))
...
>>> sublists
[[1456, 1245, 5734, 1245], [13678, 74512, 2456], [1974, 3926], [1234]]
and once you've made your output a list of lists, you could build the whole thing as a comprehension if you wanted to:
>>> original = [1234, 2456, 1245, 5734, 1245, 74512, 13678, 1456, 3926, 1974]
>>> [[original.pop(random.randrange(len(original))) for _ in range(i)] for i in range(4, 0, -1)]
[[1234, 74512, 1974, 1456], [13678, 1245, 3926], [2456, 1245], [5734]]
Another option is to shuffle the list just once so you can simply pop the last element instead of selecting a random element each time:
>>> original = [1234, 2456, 1245, 5734, 1245, 74512, 13678, 1456, 3926, 1974]
>>> random.shuffle(original)
>>> [[original.pop() for _ in range(i)] for i in range(4, 0, -1)]
[[2456, 1245, 3926, 1974], [13678, 74512, 1234], [1245, 1456], [5734]]
Upvotes: 3