不使用内置函数打乱python列表 [英] Shuffle a python list without using the built-in function

查看:37
本文介绍了不使用内置函数打乱python列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写两个不同的随机播放函数.

I'm working on writing two different shuffle functions.

第一个 shuffle 函数必须接受一个列表并返回一个新列表,其中的元素随机排列.

The first shuffle function must take a list and return a new list with the elements shuffled into a random order.

这是我迄今为止的第一个随机播放功能 -

This is what I have so far for the first shuffle function-

def shuf(List):
    import random
    newList=[]
    for i in List:
        i=random.randrange(len(List))
        newList+=i
    return newList

第二个 shuffle 函数将一个列表作为参数,并在适当的位置对列表进行洗牌.

The second shuffle function takes a list as a parameter and shuffles the list in place.

我知道如何使用内置函数执行此操作,但不允许我使用它.

I know how to do it with the built-in function but I'm not allowed to use it.

推荐答案

您可能会发现这种改组的实现适合您的需要.在使用这两个函数之前,请务必注意它们之间的区别.

You might find that this implementation for shuffling suits your needs. Make sure that you note the difference between the two functions before using them.

import copy
import random


def main():
    my_list = list(range(10))
    print(my_list)
    print(shuffle(my_list))
    print(my_list)
    shuffle_in_place(my_list)
    print(my_list)


def shuffle(container):
    new_container = copy.copy(container)
    shuffle_in_place(new_container)
    return new_container


def shuffle_in_place(container):
    for index in range(len(container) - 1, 0, -1):
        other = random.randint(0, index)
        if other == index:
            continue
        container[index], container[other] = container[other], container[index]


if __name__ == '__main__':
    main()

这篇关于不使用内置函数打乱python列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆