![](/img/trans.png)
[英]Python: repeating function that replaces x with a number (1 ~ 3) that increases with each pass
[英]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.