python-3.x 我能把这条很长的精灵链缩短吗?

laawzig2  于 2023-04-08  发布在  Python
关注(0)|答案(1)|浏览(105)
if p11 == "+":
    loc = 11
elif p12 == "+":
    loc = 12
elif p13 == "+":
    loc = 13
elif p14 == "+":
    loc = 14
elif p15 == "+":
    loc = 15

我需要把上面的从11到55,所以如果我能简化它就太棒了。变量中“p”后面的任何数字都等于loc
如果可能的话,有人能解释一下相反的情况吗?

k4ymrczo

k4ymrczo1#

我不知道你为什么会喜欢这样的东西,但无论如何,我认为你看起来像这样:

# The input variable
p11 = '+'

# Calculation of output (loc)
for variable_name, variable_value in locals().items():
    # Checking the variable name and the variable value
    if variable_value == '+' and len(variable_name) == 3 and variable_name.startswith('p') and \
            variable_name[1:3].isdigit() and 11 <= int(variable_name[1:3]) <= 55:
        loc = variable_name[1:3]
        print(loc)
        break
else:
    print('no results!')

相关问题