列表列表中的混洗对

时间:2019-11-05 19:33:27

标签: python-3.x list random shuffle

给出如下列表:

aList = [["1","Number1", "2", "Number2","3","Number3", "4", "Number4"],["3","Number3", "1", "Number1","2","Number2", "4", "Number4"]]

我正在尝试对子列表中的每两个元素进行改组,以获得类似这样的内容:

aListNew = [["3","Number3", "1", "Number1","4","Number4", "2", "Number2"],["2","Number2", "3", "Number3","1","Number1", "4", "Number4"]]

因此重要的是,两个连续的字符串在混洗时保持在一起。

1 个答案:

答案 0 :(得分:1)

您可以通过多种方式执行此操作。您没有给出任何尝试或失败原因的指示。不过,由于尚未回答或未解决此问题,因此这里有一些代码。请查看发布指南,以便您以后的发布将产生更多答案,并且不太可能被关闭。

import random

aList = [["1","Number1", "2", "Number2","3","Number3", "4", "Number4"],["3","Number3", "1", "Number1","2","Number2", "4", "Number4"]]
alist_alt = []

for sublist in aList:
    l = len(sublist)
    r = list(range(0, l ,2))
    random.shuffle(r)

    sublist_alt=[]
    for i in r:
        sublist_alt.append(sublist[i])
        sublist_alt.append(sublist[i+1])

    alist_alt.append(sublist_alt)

print(alist_alt)