14 – 乱序列表元素有哪些方式

1. 编写一个函数(不要使用python模块的函数),打乱列表元素的顺序

a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]

import random

# 方案1
def random_list1(a):
    for i in range(0, 100):
        index1 = random.randint(0, len(a)-1)
        index2 = random.randint(0, len(a)-1)
        a[index1], a[index2] = a[index2], a[index1]
    return a

b = random_list1(a)
print(b)

[4, 3, 7, 1, 9, 2, 5, 8, 0, 6]

# 方案2
def random_list2(a):
    a_copy = a.copy()
    result = []
    count = len(a)
    for i in range(0, count):
        index = random.randint(0, len(a_copy)-1)
        result.append(a_copy[index])
        del a_copy[index]
    return result

a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
b = random_list2(a)
print(b)

[4, 0, 5, 1, 2, 7, 9, 3, 8, 6]

2. 如何对列表元素进行随机排列

a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
random.shuffle(a)
print(a)

[2, 3, 1, 4, 8, 0, 9, 7, 5, 6]

正文完