如何从列表中选择随机项目,同时避免连续选择相同的项目

Err*_*Err 4 python random list

我想用随机值迭代列表.但是,我希望从列表中删除已选择的项目以进行下一次试用,以便我可以避免连续选择相同的项目; 但它应该在之后再添加.

请帮我看一下这个简单的例子.谢谢

import random
    l = [1,2,3,4,5,6,7,8]
    for i in l:
        print random.choice(l)
Run Code Online (Sandbox Code Playgroud)

eum*_*iro 9

两者都适用于非唯一元素列表:

def choice_without_repetition(lst):
    prev = None
    while True:
        i = random.randrange(len(lst))
        if i != prev:
            yield lst[i]
            prev = i
Run Code Online (Sandbox Code Playgroud)

要么

def choice_without_repetition(lst):
    i = 0
    while True:
        i = (i + random.randrange(1, len(lst))) % len(lst)
        yield lst[i]
Run Code Online (Sandbox Code Playgroud)

用法:

lst = [1,2,3,4,5,6,7,8]
for x in choice_without_repetition(lst):
    print x
Run Code Online (Sandbox Code Playgroud)