You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在嵌套列表中查找指定多米诺骨牌的索引?

查找多米诺骨牌[6,5]的索引方法

针对你给出的嵌套列表结构(外层是玩家列表,内层是每个玩家的多米诺骨牌列表),可以通过以下几种方式查找目标骨牌的索引:

1. 严格匹配(区分骨牌正反顺序)

如果需要严格匹配[6,5](即[5,6]不算匹配),可以用嵌套遍历结合index方法快速定位:

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

# 遍历每个玩家的手牌
for player_index, hand in enumerate(list_of_hand):
    if target_domino in hand:
        # 获取骨牌在当前玩家手牌中的索引
        domino_index = hand.index(target_domino)
        print(f"目标骨牌位置:玩家索引 {player_index},手牌内索引 {domino_index}")
        # 若需返回结果,可存储为元组:(player_index, domino_index)
        break
else:
    # 循环正常结束(未触发break),说明没找到
    print("未找到目标多米诺骨牌")

运行这段代码会输出:目标骨牌位置:玩家索引 0,手牌内索引 2,和示例中的位置完全一致。

2. 模糊匹配(不区分骨牌正反顺序)

多米诺骨牌通常不分正反,比如[6,5]和[5,6]会被视为同一张牌。这种情况下,可以通过比较排序后的骨牌或集合来匹配:

方法一:用排序后的元组比较

list_of_hand = [[[2, 5], [5, 5], [6, 5], [6, 4]], [[3, 2], [4, 5], [4, 4], [6, 1]]]
target_domino = [5, 6]  # 与[6,5]是同一张骨牌

for player_index, hand in enumerate(list_of_hand):
    for domino_index, domino in enumerate(hand):
        if sorted(domino) == sorted(target_domino):
            print(f"匹配骨牌位置:玩家索引 {player_index},手牌内索引 {domino_index}")
            break
    else:
        continue
    break
else:
    print("未找到匹配的多米诺骨牌")

方法二:用集合比较(仅适用于骨牌元素为不可变类型,比如整数)

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

for player_index, hand in enumerate(list_of_hand):
    for domino_index, domino in enumerate(hand):
        if set(domino) == set(target_domino):
            print(f"匹配骨牌位置:玩家索引 {player_index},手牌内索引 {domino_index}")
            break
    else:
        continue
    break
else:
    print("未找到匹配的多米诺骨牌")

3. 查找所有匹配的位置

如果列表中存在多个相同的目标骨牌,想要获取所有位置,可以收集所有符合条件的索引对:

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

for player_index, hand in enumerate(list_of_hand):
    for domino_index, domino in enumerate(hand):
        if domino == target_domino:
            all_positions.append( (player_index, domino_index) )

if all_positions:
    print(f"所有匹配的位置:{all_positions}")
else:
    print("未找到目标多米诺骨牌")

运行后会输出:所有匹配的位置:[(0, 1), (0, 3), (1, 0)]


内容的提问来源于stack exchange,提问作者Maxime Morin-Gagnon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 04:27:30