0

我必须通过将列表拆分为两个列表然后将其洗牌 n 次来洗牌。我无法为两个列表创建一个 for 循环来随机播放(对于 n 的范围),因为无论 n 是什么。它只洗牌一次。这是我的函数代码:

def shuffle(xs,n=1):
il=list()
if len(xs)%2==0:
    stop=int(len(xs)//2)
    a=xs[:stop]
    b=xs[stop:]
else:
    stop=int(len(xs)//2)
    a=xs[:stop]
    b=xs[stop:]
if n>0:
    for i in range(n):
        shuffle=interleave(a,b)
else:
    return 
return shuffle

我的交错函数是之前定义的,并且似乎工作正常。

4

1 回答 1

0

假设您想要交错列表,您可以编写一个简单的递归函数来执行 n 次。交错列表的一件事是第一个和最后一个字符将始终相同,我相信。

def shuffle(lst, num):
    '''
    lst - is a list
    num - is the amount of times to shuffle
    '''
    def interleave(lst1,lst2):
        '''
        lst1 and lst2 - are lists to be interleaved together
        '''
        if not lst1:
            return lst2
        elif not lst2:
            return lst1
        return lst1[0:1] + interleave(lst2, lst1[1:])
    while num > 0:
        lst = interleave(lst[:len(lst)/2], lst[len(lst)/2:])
        print lst
        num -= 1
    return lst
于 2013-11-11T08:35:00.607 回答