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

如何简化size值与:nth-child序号映射的重复if判断代码

方案1:规则计算法(最简洁,适合规则固定的场景)

直接按照你给出的规则计算nth-child的索引,无需维护冗余的分支判断:

size_num = int(size)
nth_index = (size_num - 6) // 2 + 1
element = f'#pdp__select-size > li:nth-child({nth_index}) > button'

如果需要增加输入合法性校验,避免非法size生成无效选择器,可以扩展为:

size_num = int(size)
# 校验size是否在合法的偶数范围内
if 6 <= size_num <= 18 and size_num % 2 == 0:
    nth_index = (size_num - 6) // 2 + 1
    element = f'#pdp__select-size > li:nth-child({nth_index}) > button'
else:
    raise ValueError(f"不支持的尺码值: {size}")

方案2:字典映射法(更灵活,适合规则可能变动的场景)

如果后续可能调整尺码和索引的对应关系,用字典维护映射关系更易维护:

size_to_index = {
    "6": 1, "8": 2, "10": 3, "12": 4,
    "14": 5, "16": 6, "18": 7
}
element = f'#pdp__select-size > li:nth-child({size_to_index[size]}) > button'

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 17:06:04