从列表/变量中取出一个元素

30 浏览
0 Comments

从列表/变量中取出一个元素

这个问题已经有了答案:

删除列表上 del、remove、pop 的区别

我尝试在玩家的牌已经发出后从牌堆中取走一张牌,这样这些牌就不会再次发出。

import random    
import time      
cards = ["Ace of Hearts", "Ace of Diamonds", "Ace of Clubs", "Ace of Spades", "King of Hearts", "King of Diamonds", "King of Clubs", "King of Spades", "Queen of Spades", "Queen of Hearts", "Queen of Clubs", "Queen of Diamonds", "Jack of Hearts", "Jack of Diamonds", "Jack of Clubs", "Jack of Spades", "Ten of Hearts", "Ten of Diamonds", "Ten of Clubs", "Ten of Spades", "Nine of Hearts", "Nine of Diamonds", "Nine of Clubs", "Nine of Spades", "Eight of Hearts", "Eight of Diamonds", "Eight of Clubs", "Eight of Spades", "Seven of Hearts", "Seven of Diamonds", "Seven of Clubs", "Seven of Spades", "Six of Hearts", "Six of Diamonds", "Six of Clubs", "Six of Spades", "Five of Hearts", "Five of Diamonds", "Five of Clubs", "Five of Spades", "Four of Hearts", "Four of Diamonds", "Four of Clubs", "Four of Spades", "Three of Hearts", "Three of Diamonds", "Three of Clubs", "Three of Spades", "Two of Hearts", "Two of Diamonds", "Two of Clubs", "Two of Spades"]
p1c = random.choice(cards)
cards = cards - p1c
p2c = random.choice(cards)
cards = cards - p2c

但是这里出现了我的命令错误:

  File "", line 26, in 
TypeError: unsupported operand type(s) for -: 'list' and 'str'
[Program finished]

admin 更改状态以发布 2023年5月25日
0
0 Comments

我认为你应该使用remove()来从列表中移除元素,或使用关键字del

remove()
cards.remove(p1c)

del

place=cards.index(p1c)#or you can give p2c
del cards[place]

谢谢
- Levers

0
0 Comments

我认为您正在寻找remove(),它可以从列表中移除元素:

cards.remove(p1c)

0