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

时间:2019-07-09 16:11:50

标签: python arrays random repeat

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

4 个答案:

答案 0 :(得分:1)

两件事之一应该很有效,

(1)复制列表;从副本中选择项目。每次选择一个项目时,将其从列表中删除。当您清空列表时,请制作一个新副本并继续。

(2)使用itertools中的改组操作为列表提供随机排列。遍历。到最后,获得一个新的随机排列。

答案 1 :(得分:1)

您应使用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()使列表的顺序随机化,并根据需要再次遍历列表。

答案 2 :(得分:0)

您要像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)

答案 3 :(得分:0)

您可以尝试一下

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