Python从数组中随机选择名称,不重复,直到选择完所有名称为止

2024-05-16 11:57:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我刚刚开始学习Python,所以如果这很简单,我很抱歉。我想从一组名称数组中生成一个随机名称,然后在选择所有名称并再次开始循环之前,不要重复该名称。下面的代码是我已经有了,这产生了随机名称,但重复正在发生。你知道吗

import random

employee = ["adam", "Scott", "Michael", "Andrew", "Mark", "Fernando", "Faith", "Steve", "Lee", "Amani", "Liv", "Nick A", "James", "Jake", "Brett", "Graham", "Fraser", "Jacob", "Chelsea", "Phil", "George", "Charley", "Emma", "Steph"]
print(random.choice(employee))

Tags: 代码import名称employeerandom数组scottsteve
3条回答

您应该使用^{}来无序排列列表中的元素:

import random

employee = ["adam", "Scott", "Michael", "Andrew", "Mark", "Fernando", "Faith", "Steve", "Lee", "Amani", "Liv", "Nick A", "James", "Jake", "Brett", "Graham", "Fraser", "Jacob", "Chelsea", "Phil", "George", "Charley", "Emma", "Steph"]
random.shuffle(employee)
for i in employee:
    print(i)

您可以使用random.shuffle()来随机化列表的顺序,并根据需要在列表上重复多次。你知道吗

您想像使用in-place random shuffling of a list一样使用random.shuffle

import random

employee = ["adam", "Scott", "Michael", "Andrew", "Mark", "Fernando", "Faith", "Steve", "Lee", "Amani", "Liv", "Nick A", "James", "Jake", "Brett", "Graham", "Fraser", "Jacob", "Chelsea", "Phil", "George", "Charley", "Emma", "Steph"]

# Make 10 rounds of random selections
for i in range(10):
    print(i)
    # Shuffle the list in new random order
    random.shuffle(employee)
    # Print a random employee without repetition in each round
    for random_employee in employee:
        print(random_employee)

两件事中的一件应该起作用,非常相似:

(1)复制清单;从副本中选择项目。每次选择项目时,都要将其从列表中删除。清空列表后,制作新副本并继续。你知道吗

(2)使用itertools中的洗牌操作来对列表进行随机排列。重复一遍。当你到最后,得到一个新的随机排列。你知道吗

相关问题 更多 >