我有一个包含多米诺骨牌的列表(那些也是两个整数的列表),我需要找到一个多米诺骨牌的索引

例:

list_of_hand = [[[2, 5], [5, 5], [6, 5], [6, 4]], [[3, 2], [4, 5], [4, 4], [6, 1]]]


该列表是两个列表,其中包括玩家手中所有的多米诺骨牌。

如何找到多米诺[6, 5]的索引?

最佳答案

您可以使用一个简单的函数来搜索子列表:

x = [[[2, 5], [5, 5], [6, 5], [6, 4]], [[3, 2], [4, 5], [4, 4], [6, 1]]]

def hand_search(L, domino):
    for s in L:
        if domino in s:
            return (L.index(s), s.index(domino))
    return -1

print(hand_search(x, [6,5]))
print(hand_search(x, [6,1]))


输出:

(0, 2)    # 0 is the player, 2 is the position in their hand
(1, 3)    # 1 is the player, 3 is the position in their hand


只要嵌套相同,就可以根据需要扩展到任意数量的玩家。

09-17 19:09