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

如何获取列表中指定值的多个索引?(卡牌计分场景)

获取列表中指定值的所有索引方法

方法一:列表推导式(简洁高效)

利用enumerate()同时遍历列表的索引和元素,筛选出值等于目标值的索引:

my_list = [5, 1, 5]
list_max = max(my_list)
# 收集所有等于最大值的索引
list_max_indices = [idx for idx, value in enumerate(my_list) if value == list_max]

执行后list_max_indices会得到[0, 2],包含所有匹配值的索引。

方法二:手动循环收集(直观易懂)

如果需要更清晰的逻辑,可以用普通循环逐个判断并收集索引:

my_list = [5, 1, 5]
list_max = max(my_list)
list_max_indices = []
for i in range(len(my_list)):
    if my_list[i] == list_max:
        list_max_indices.append(i)

适配你的卡牌计分场景

将上述方法应用到你的卡牌程序中,完整代码示例:

score = [0, 0, 0]
players = ["user", "first_opponent", "second_opponent"]
# 假设这是各玩家的对局得分
player_scores = [5, 3, 5]

max_score = max(player_scores)
winning_indices = [idx for idx, s in enumerate(player_scores) if s == max_score]

# 为所有获胜玩家加分
for idx in winning_indices:
    score[idx] += 1

print(score)  # 输出结果:[1, 0, 1]

内容的提问来源于stack exchange,提问作者Yes

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 16:12:34