在列表列表中查找匹配的前导值

2024-06-16 04:57:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一份清单。它们一开始是空列表,在我的程序中,我通过在前面插入值来添加到列表中。这是一个纸牌游戏。类似于纸牌游戏。因此,列表以a开头,以国王结尾。我现在要做的是确定玩家何时真正赢得了比赛,这意味着国王是名单中每个名单的第一张牌。我做这件事有困难。目前,当我循环使用我的函数时,一旦一个列表具有king值,它就会让我知道我赢了

BANNER = WINNER!!
foundations = [ [], [], [], [] ]

for lst in foundations[:]:
    for item in lst:
        if item.rank() == 13: # the rank of a king
            print(BANNER)
            return True
else:
    return False

我要找的是:

when foundations = [ [13], [13], [13], [13] ] # all four list containing king

then the loop returns True

如何阻止代码给我错误的希望并让我知道何时我真的赢了游戏


Tags: thein游戏列表forreturnitembanner
1条回答
网友
1楼 · 发布于 2024-06-16 04:57:14

问题是,只要if item.rank() == 13条件为True,您就可以从函数返回,这还不足以获胜

您似乎也在单步遍历所有列表值,但只需要单步遍历每个列表中的第一个值

所以你要找的代码是

for list in foundations:
    if list[0] != 13:
        return False  # this is definitely not a win
return True # this code will only work if return False didn't work

在本例中,我假设每个list至少有一个值。根据您的问题,您可能希望绕过此假设

相关问题 更多 >