首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >数字X增加1,如果数字增加2

数字X增加1,如果数字增加2
EN

Stack Overflow用户
提问于 2021-11-10 17:27:15
回答 1查看 41关注 0票数 0

我怎样才能使下面的代码更短呢?

代码语言:javascript
复制
if size == "6":
        element = '#pdp__select-size > li:nth-child(1) > button'

if size == "8":
        element = '#pdp__select-size > li:nth-child(2) > button'

if size == "10":
        element = '#pdp__select-size > li:nth-child(3) > button'

if size == "12":
        element = '#pdp__select-size > li:nth-child(4) > button'

if size == "14":
        element = '#pdp__select-size > li:nth-child(5) > button'

if size == "16":
        element = '#pdp__select-size > li:nth-child(6) > button'

if size == "18":
        element = '#pdp__select-size > li:nth-child(7) > button'

基本上,每次大小增加2(从6> 8)等等...我希望元素中的数字增加1(来自1>2),等等。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-11-10 17:34:44

size转换为整数并执行一些算术运算,以获得nth()中的值。

代码语言:javascript
复制
size_int = int(size)
if size_int % 2 == 0 and 6 <= size_int <= 18:
    # size is even
    nth = size_int//2 - 2
    element = f"#pdp__select-size > li:nth-child({nth}) > button"
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69917668

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档