Skip to main content
 首页 » 编程设计

python之列表排序-Python纸牌游戏

2024年09月07日6duanxz

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

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

请您参考如下方法:

出于解释原因对代码进行注释,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