I want to find random couples on a single list with different members.
Here is my code:
import random
def alea_couple(members):
couples = []
for p in members:
possibles = [r for r in members if r!=p and r not in [elem[1] for elem in couples]]
couples.append((p, random.choice(possibles)))
return couples
my_members = ["member1", "member2", "member3", "member4"]
random.shuffle(my_members)
alea_couple(my_members)
[('member2', 'member1'),
('member3', 'member4'),
('member1', 'member3'),
('member4', 'member2')]
I am sure there is a better way and more elegant way to do this with itertools.combinations
do you have a piece of advice ?
Aucun commentaire:
Enregistrer un commentaire