簡體   English   中英

如果數字增加 2,則將數字 X 增加 1

[英]Increase number X by 1, if number increases by 2

我怎樣才能使下面的代碼更短?

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)等等。

size轉換為整數並執行一些算術運算以獲取nth()的值。

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"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM