如何在python中正确地重新排列列表

时间:2013-11-10 16:34:18

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

我有这个代码可以随机播放一个列表。我首先将它分成两个列表,因为我有一个交错函数,交错2个列表:

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

当我测试它时:

>>> shuffle([1,2,3,4,5,6,7],1)
[1, 2, 3]
[4, 5, 6, 7]
1
[7]
[7, 4]
[1, 4, 2, 5, 3, 6, 7, 4]

列表中的4是两次,为什么打印1,[7],7,4] ??

编辑:

def interleave(xs,ys):
    a=xs
    b=ys
    minlength=[len(a),len(b)]
    extralist= list()
    interleave= list()
    for i in range((minval(minlength))):
        pair=a[i],b[i]
        interleave.append(pair)
        flat=flatten(interleave)
        c=a+b
    if len(b)>len(a):
        remainder=len(b)-len(a)
        for j in range(remainder,-1,-1):
            extra=b[-j]
            extralist.append(extra)
    if len(a)>len(b):
        remainder=len(a)-len(b)
        for j in range(remainder,-1,-1):
            extra=a[-j]
            extralist.append(extra)
    del extralist[-1]
    final=flat+extralist
    return final

2 个答案:

答案 0 :(得分:7)

为什么不使用标准库?

>>> from random import shuffle
>>> l = list(range(1,20))                                                                                                                                                                                                                       
>>> l
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
>>> shuffle(l)                                                                                                                                                                                                                                  
>>> l
[17, 15, 9, 13, 19, 7, 10, 18, 5, 1, 12, 3, 2, 16, 4, 14, 8, 6, 11]
>>> 

答案 1 :(得分:0)

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

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