列出排序的Python纸牌游戏

问题描述 投票:2回答:1

我有一个纸牌游戏,其中包含从上到下的玩家手中的牌列表,我需要检查牌列表从小到大(从上到下)的顺序。我无法使用任何类型的GUI。

例如,玩家手中的牌:23 24 12 5 - 检查列表中正确排序的第五个元素4 3 2 1

python python-3.x list
1个回答
2
投票

代码评论说明原因,hth:

cardsInHand = [23,24,25,23,27,4]  # all your cards

cardsInOrder = []                 # empty list, to be filled with in order cards
lastCard = None  

for card in cardsInHand:                  # loop all cards in hand
    if not lastCard or lastCard < card:       # if none taken yet or smaller
        cardsInOrder.append(card)                 # append to result
        lastCard = card                           # remember for comparison to next card
    else:                                     # not in order
        break                                     # stop collecting more cards into list 

print(cardsInOrder)               # print all

输出:

[23, 24, 25]

如果您还需要手的无序部分,您可以通过以下方式获得:

unorderedCards = cardsInHand[len(cardsInOrder):] # list-comp based length of ordered cards
© www.soinside.com 2019 - 2024. All rights reserved.