从列表列表中随机抽样

时间:2020-12-03 19:45:38

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

在python中,我有一个列表列表x,如下所示:[[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]

我有另一个清单,y,像这样[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:

我需要从y中得到两个不在x列表中的随机项,所以我可以在x中切换它们,其目标是[[1,2,9],[4,5,6] ,[7,8,3]]。我目前的方法如下:

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?

indexInCourse是一个函数,它返回一个项目在列表列表中的列表,因此对于(x,1)它将返回0.目标是切换器是2个不同的数字,在整个不同的列表中,所以像[1,9]或[4,7]。我当前的方法有效,但对于我经历过的大量列表来说速度非常慢。有没有人知道更多的pythonic方式来做到这一点?

1 个解决方案

#1


2  

Why not randomly pick two distinct lists from x first and then swap a random choice of two elements between them?

为什么不首先从x中随机选择两个不同的列表,然后在它们之间交换随机选择的两个元素?

lists = random.sample(x, 2)
# now we swap two random elements between lists[0], lists[1]

#1


2  

Why not randomly pick two distinct lists from x first and then swap a random choice of two elements between them?

为什么不首先从x中随机选择两个不同的列表,然后在它们之间交换随机选择的两个元素?

lists = random.sample(x, 2)
# now we swap two random elements between lists[0], lists[1]