繁体   English   中英

Append 随机从list1到list2中的一个元素,然后同时从list1中删除这个元素

[英]Append an element from list1 to list2 randomly then delete this element from list1 at the same time

例如:

Cards = 13       
    while Cards > 0:
        card1 = ["FLOUR", "MONKEY", "DOLLAR", "LOVE", "POISON"]
        print ("Aktive Player: enter a number between 1 and 5 to choose the Mystry word")
    
        Mystry = []
        x = ["1", "2", "3", "4", "5"]
        while True:
            response = input('>')
            if response not in x:
                print ("Aktive Player: enter a number between 1 and 5 to choose the Mystry word")
            else:
                Mystry = random.choice(card1)
                break

print(Mystry)
print(card1)

如果 Mystry = "FLOUR",如何从 card1 中删除 "FLOUR",这样它就不会出现在下一个循环中?

您可以使用 Python 的list.pop()方法 - 来自文档

list.pop([i])

Remove the item at the given position in the list, and return it.
If no index is specified, a.pop() removes and returns the last item in the list. 
(The square brackets round the i in the method signature denote that the parameter is optional,
not that you should type square brackets at that position.
You will see this notation frequently in the Python Library Reference.)

基本上,您将项目添加到Mystery的代码应如下所示:

Mystery = card1.pop(random.choice(range(0, len(card1))))

您可以将列表随机排列,将第一项分配给Mystry ,然后将 rest 分配回card1

random.shuffle(card1)
Mystry, *card1 = card1

您可以使用 index() 方法找到您最后选择的索引,而不是使用 pop(ind) 使用找到的索引的参数删除它。 下面的例子

Cards = 13       
    while Cards > 0:
        card1 = ["FLOUR", "MONKEY", "DOLLAR", "LOVE", "POISON"]
        print ("Aktive Player: enter a number between 1 and 5 to choose the Mystry word")
    
        Mystry = []
        x = ["1", "2", "3", "4", "5"]
        while True:
            response = input('>')
            if response not in x:
                print ("Aktive Player: enter a number between 1 and 5 to choose the Mystry word")
            else:
                Mystry = random.choice(card1)
                ind = card1.index(Mystry)
                card1.pop(ind)
                break

print(Mystry)
print(card1)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM