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

Python中如何匹配元组与字典键以确定迭代起始位置?

检查元组键与字典匹配并确定迭代起始位置的方法

1. 验证元组中的键是否存在于嵌套字典中

要确认first_try的两个元素分别对应medication的外层键和内层键,直接用in操作符做存在性检查即可:

outer_key, inner_key = first_try

# 先检查外层类别是否存在,再检查该类别下的子药物是否存在
if outer_key in medication and inner_key in medication[outer_key]:
    print("起始药物在字典中存在")
else:
    print("起始药物不存在,请检查元组或字典定义")

2. 生成符合要求的完整药物遍历顺序

Python 3.7及以上版本的字典会保留插入顺序,直接按层级遍历就能生成指定顺序的药物路径列表:

# 生成按A-i、A-ii、B-i、B-ii顺序的药物路径列表
full_med_sequence = []
for category in medication:
    for sub_category in medication[category]:
        full_med_sequence.append( (category, sub_category) )
# 输出结果:[("A","i"), ("A","ii"), ("B","i"), ("B","ii")]

3. 找到起始位置并开始遍历

用列表的index()方法定位first_try的位置,之后从该点开始遍历,甚至可以循环遍历整个列表直到达到maximum_time:

# 获取起始索引(需提前做存在性检查,避免抛出ValueError)
start_index = full_med_sequence.index(first_try)

total_elapsed_time = 0
current_index = start_index

while total_elapsed_time < maximum_time:
    # 获取当前要给药的药物路径
    current_cat, current_subcat = full_med_sequence[current_index]
    drug_details = medication[current_cat][current_subcat]
    drug_half_life = drug_details["half-life"]
    
    # 执行给药逻辑(示例为累加时间)
    total_elapsed_time += drug_half_life
    print(f"给药:{current_cat}-{current_subcat},半衰期{drug_half_life},累计时间{total_elapsed_time}")
    
    # 移动到下一个药物,到达列表末尾后循环到开头
    current_index = (current_index + 1) % len(full_med_sequence)

关键注意事项

  • 必须先做键的存在性检查,避免index()方法抛出异常
  • 若使用Python 3.6及以下版本,字典不保证插入顺序,需要用collections.OrderedDict定义medication以确保顺序正确

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 01:01:19