Skip to content

编写一个函数(不使用Python模块中的函数),打乱列表元祖的顺序 #30

@Sogrey

Description

@Sogrey

编写一个函数,用于随机排列列表中的元素

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)  ## [5, 7, 0, 3, 1, 8, 4, 2, 6, 9]
# 方案2
def random_list2(a):
    a_copy = a.copy() # 先复制一份
    result = []
    count = len(a)  #得到a的长度
    for i in range(0,count): 
        index = random.randint(0, len(a_copy) - 1)
        result.append(a_copy[index])  #随机得到a中一个元素存到结果中
        del a_copy[index]  # 删除这个随机的幸运儿元素 直到全部删除完,结束循环
    return result
a = [1,2,3,4,5,6,7, 8, 9,0 ]
b = random_list2(a)
print(b)  ## [5, 2, 6, 7, 0, 1, 9, 8, 3, 4]

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions