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

如何直接从二维列表Aliances中获取PK=10012的索引位置?

直接从Aliances列表获取指定PK的索引位置

是的,完全可以不用先提取PKs列表,直接从Aliances列表中找到对应PK的索引位置。以下是几种高效实现方式:

方法一:使用enumerate遍历

通过enumerate同时获取索引和列表中的元组,遍历过程中检查元组的第一个元素是否匹配目标PK:

target_pk = 10012
index = -1
for idx, alliance in enumerate(Aliances):
    if alliance[0] == target_pk:
        index = idx
        break

if index != -1:
    myDialog.comboBox_Alliance.setCurrentIndex(index)
else:
    # 处理PK不存在的情况,比如设置默认索引
    myDialog.comboBox_Alliance.setCurrentIndex(0)

方法二:生成器表达式(更简洁)

利用next()结合生成器表达式,直接定位第一个匹配的索引:

target_pk = 10012
try:
    index = next(idx for idx, alliance in enumerate(Aliances) if alliance[0] == target_pk)
    myDialog.comboBox_Alliance.setCurrentIndex(index)
except StopIteration:
    # PK不存在时的 fallback 逻辑
    myDialog.comboBox_Alliance.setCurrentIndex(0)

优势对比

相比原代码的实现方式:

  • 无需额外创建PKs列表,节省内存空间
  • 仅需遍历一次列表,执行效率更高
  • 代码逻辑更紧凑,减少中间变量的维护成本

整合到原代码的示例

替换原代码中获取索引的部分:

Aliances = S.QueryAliances()
print("Aliances=" + str(Aliances))
myDialog.comboBox_Alliance.clear()
if Aliances:
    for Aliance in Aliances:
        myDialog.comboBox_Alliance.addItem(str(Aliance[1]))
    
    # 直接获取目标PK的索引
    target_pk = A.Aliance
    try:
        index = next(idx for idx, alliance in enumerate(Aliances) if alliance[0] == target_pk)
        print("index=" + str(index))
        myDialog.comboBox_Alliance.setCurrentIndex(index)
    except StopIteration:
        print("目标PK未找到")
        myDialog.comboBox_Alliance.setCurrentIndex(0)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 09:30:56