我在不使用其他解决方案的情况下制作自己的二十一点游戏。这只是代码的一部分,因为我正在逐步进行工作。我想合并一张纸牌清单,以便为每个玩家创建一个新清单。我有第一张发给4位玩家的纸牌:
shuffled_deck = [['A', '♦'], ['6', '♣'], ['2', '♥'], ['Q', '♦'], ['K', '♦'], ['3', '♠'], ['8', '♠'], ['9', '♠']]
players = [[1], [2], [3], [4]]
期望的输出>>
[[['A', '♦'], ['K', '♦']], [['6', '♣'], ['3', '♠']], [['2', '♥'], ['8', '♠']], [['Q', '♦'], ['9', '♠']]]
它只是向21位玩家分发两张牌,就像二十一点一样。我可以使用以下方法创建它:
#EXAMPLE 1
for i in range(0,4):
players[i] = [shuffled_deck[i]]
for j in range(0,4):
players[j].append(shuffled_deck[j+4])
但是我想用这样的方法来做,但是不知道怎么做。
count = 0
people = []
def combine_2_cards(people=[], count=count):
while count < 8:
people.append(shuffled_deck.pop(0))
count += 1
return combine_2_cards(people, count)
return people
players = combine_2_cards(people, count)
这只是创建原始的shuffled_cards列表。也许还有更好的方法?
我需要使其像期望的输出中一样追加。
这是如何工作的:首先,递归的基本情况是当卡片为空时,经典的“如果(基本情况下)其他(做某事)”,我们正在检查纸牌列表是否为空,我们将填充玩家
如何填充玩家:从cards
列表中弹出2张卡,当i为0时,弹出第一个元素,当i为1时,弹出中间卡,然后将两者都作为列表添加到卡列表中]]
一遍又一遍,直到达到基本情况。
def combine_2_cards(players, cards):
if cards:
# assign 2 cards to 1 players
current_cards = [card for card in [cards.pop(0 if i % 2 == 0 else len(cards) // 2) for i in range(2)]]
players.append(current_cards)
combine_2_cards(players, cards)
return players
print(combine_2_cards([], shuffled_deck))
# prints: [[['A', '♦'], ['K', '♦']], [['6', '♣'], ['3', '♠']], [['2', '♥'], ['8', '♠']], [['Q', '♦'], ['9', '♠']]]
您可以使用slice(i, None, x)
从第x
个元素开始获取每个第i
个元素。
非常感谢@pidgeyUsedGust和@Fibi。虽然我还没有理解能力,但是我认为我现在可以更好地理解它们。我还运行了两次函数,并创建了所需的输出,如下所示,