Python - 从数组中选择随机名称,不重复,直到全部被选择

Python - Choose random name from array without repetition until all have been chosen

我刚刚开始学习 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))

您想按原样使用 random.shuffle in-place random shuffling of a list

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 中的混洗操作为您提供列表的随机排列。遍历那个。当你走到尽头时,获得一个新的随机排列。

你可以试试这个,

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"]

employeecopy = employee

while len(employeecopy) != 0:
  chosen = random.choice(employeecopy)
  employeecopy = list(set(employeecopy) - set([chosen]))

查看实际效果 here

您应该使用 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"]
random.shuffle(employee)
for i in employee:
    print(i)

您可以使用 random.shuffle() 随机化列表的顺序,并根据需要再次遍历列表。