我正在尝试创建一个发卡程序,但是遇到了一些困难。 我的代码如下:
cards = ["ace of spades", "ace of hearts", "2 of diamonds"] etc...
firstcard = random.choice(cards)
del cards[firstcard]
print(firstcard)
我试图同时删除从阵列中选择的卡并进行存储(以便删除该卡,以免再次处理),以便进行打印。
我一直收到此错误: TypeError:列表索引必须是整数或切片,而不是str ,但是我不确定是否有其他函数可以帮助我。
谢谢!
答案 0 :(得分:1)
您可以使用random.randrange
从列表中随机选择项目,然后使用列表pop
函数将其从列表中删除:
import random
cards = ["ace of spades", "ace of hearts", "2 of diamonds"]
print(cards.pop(random.randrange(len(cards)))) # Randomly removed item.
print(cards) # List after removal of the random item.
答案 1 :(得分:0)
您可能会考虑使用random.sample(cards, len(cards))
来生成按随机顺序排列的新列表。这样可以避免更改原始的cards
列表。参见https://docs.python.org/dev/library/random.html#random.sample
答案 2 :(得分:0)
因此,我在这里详细说明了您的代码。我最初对您的问题有一种误读,但只是通过合并最终列表来添加一个简单的解决方法。这应该以随机顺序将卡返回到新列表中...如果您要这样做的话?在分发卡片方面,您应该可以简单地通过名为 shuffled_cards 的新列表中的每张卡片创建 for循环和迭代 。希望这会有所帮助,或至少会有所帮助!
import random
cards = ["ace of spades", "ace of hearts", "2 of diamonds"]
list_of_del_cards = []
i = 0
#while loop based on the number of cards in the list
while i < len(cards):
selected_card = random.choice(cards) #randomly select card from list
list_of_del_cards.append(selected_card) #append randomly selected card to a new list
pos_in_list = cards.index(selected_card) #find pos of this card in old list
del cards[pos_in_list] #del card from old list
i += 1 #increment i each time to complete while loop
print(cards) #prints the list with the card that is left
print(list_of_del_cards) #print the list of deleted cards in order
shuffled_cards = list_of_del_cards + cards
print(shuffled_cards)
答案 3 :(得分:0)
“我要尝试的是按顺序打印每张卡,就像发牌人将其一张一张地放置。有没有办法直接移动字符串并将其放在另一个名为发卡?” -OP
可以使用或不使用额外的列表来完成此任务,但是如果您想存储值(例如说此样本较大并且您要存储52个样本中的12个),那么我也提供了该解决方案。
没有多余的列表:
import random
cards = ["ace of spades", "ace of hearts", "2 of diamonds"]
while len(cards) > 0:
print(cards.pop(random.randrange(len(cards))))
带有额外的列表“ dealt_cards” :
import random
dealt_cards = []
while len(cards) > 0:
x = cards.pop(random.randrange(len(cards)))
dealt_cards.append(x)
print(x)
print('Dealt Cards: {}'.format(dealt_cards))
2 of diamonds ace of hearts ace of spades Dealt Cards: ['2 of diamonds', 'ace of hearts', 'ace of spades']