jeudi 9 juin 2016

Random sample from list of lists

In python, I have a list of lists, x, like so: [[1, 2, 3],[4, 5, 6], [7, 8, 9]]

I have another list, y, like so [1, 2, 3, 4, 5, 6, 7, 8, 9]

I need to get 2 random items from y that are not together in a list in x, so I can switch them around in x, with the goal being something like [[1, 2, 9], [4, 5, 6], [7, 8, 3]]. My current method is as follows:

done = False
while not done:
    switchers = random.sample(y, 2)
    if indexInCourse(x, switchers[0]) != indexInCourse(course, switchers[1]):
        done = True

indexInCourse is a function that returns which list an item is in in a list of lists, so for (x, 1) it will return 0. The goal is for switchers to be 2 different numbers that are in different lists in the whole, so like [1, 9] or [4, 7]. My current method works, but is very slow for the large amount of lists I have going through it. Does anyone know of a more pythonic way to do this?




Aucun commentaire:

Enregistrer un commentaire