【问题标题】:How to shuffle with "n" number of times如何以“n”次随机播放
【发布时间】:2013-11-11 02:46:06
【问题描述】:

我必须通过将列表拆分为两个列表然后将其随机播放 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

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

【问题讨论】:

  • 是什么让你认为列表只被洗牌一次?如果你要在里面做完全相同的事情,为什么你的 for 循环中有 if 语句?
  • 使用与shuffle 不同的变量名。另外,确保每个代码块中都有一个return
  • @justhalf 我编辑了它。那只是我在操纵它。这就是我所拥有的,它只会洗牌一次

标签: python for-loop python-3.x user-defined-functions


【解决方案1】:

假设您想要交错列表,您可以编写一个简单的递归函数来执行 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-23
    • 1970-01-01
    • 1970-01-01
    • 2011-01-27
    相关资源
    最近更新 更多