繁体   English   中英

交错排列列表,直到它恢复为Python的原始顺序

[英]Interleave shuffle a list until it returns to original order in Python

我正在尝试交错播放一副纸牌。 例如,[1,2,3,4,5,6]被切成两半,分为[1,2,3]和[4,5,6],然后改组为[1,4,2,5,3 ,6]。 为此,我有:

listA = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 
19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 
37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52]
listLen = len(listA)/2
listB = listA[:listLen]
listC = listA[listLen:]
listD = []
num = 0

while num < listLen:
    if len(listB) >= num:
        listD.append(listB[num])
        listD.append(listC[num])
    num += 1
if len(listA)%2 != 0:
    listD.append(listC[num])
print listD

现在我的问题是,我该如何获取listD(混洗后的卡片)并重复此过程,直到回到原始顺序(1、2、3、4 ...)? 并打印出发生的洗牌数量。

listA = [1,2,3,4...]

while ListD!=ListA:
    while num < listLen:
    if len(listB) >= num:
        listD.append(listB[num])
        listD.append(listC[num])
    num += 1
    if len(listA)%2 != 0:
    listD.append(listC[num])
    print listD

只需将所有代码放入while循环中,即可检查ListD何时等于ListA。 (停止时它们将是相同的)

如何使用列表切片分配

def shuf(cards):
    half = len(cards) // 2
    res = cards[:]
    res[::2] = cards[:half]
    res[1::2] = cards[half:]
    return res

首先,我们创建原始列表的浅表副本(使用cards[:] )(只是为了获得相同大小的“可写”列表)。 然后,将初始列表的下半部分分配给结果列表的偶数索引( res[::2] ),并将上半部分分配给奇数索引( res[1::2] )。

例如:

>>> x = range(1,7); x
[1, 2, 3, 4, 5, 6]
>>> x = shuf(x); x
[1, 4, 2, 5, 3, 6]
>>> x = shuf(x); x
[1, 5, 4, 3, 2, 6]
>>> x = shuf(x); x
[1, 3, 5, 2, 4, 6]
>>> x = shuf(x); x
[1, 2, 3, 4, 5, 6]

完整的解决方案。

listA = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 
19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 
37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52]

listE = listA
listD = []
amountOfShuffles = 0
while listE != listD:
    num = 0
    listD = []
    listLen = len(listA)/2
    listB = listA[:listLen]
    listC = listA[listLen:]
    while num < listLen:
        if len(listB) >= num:
            listD.append(listB[num])
            listD.append(listC[num])
        num += 1
    if len(listA)%2 != 0:
        listD.append(listC[num])
    listA = listD
    amountOfShuffles += 1

print 'No of shuffles :',amountOfShuffles

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM