python—编写代码的更好方法?将多个变量设置为字典中一个str(键)的值

nfeuvbwi  于 2021-07-14  发布在  Java
关注(0)|答案(2)|浏览(220)

我编写了以下函数。输出值应作为api请求中参数的一部分使用

def zeitraum():
    x = input("How many month? Choose between 1 and 24 \n")
    y = []
    z = {'a string key':y}
    for i in range(1,int(x)+1):
        if int(x) > 24:
            x = input("Choose between 1 and 24. \n")
        if i <= 12:
            x = f'year1month{i}'
            y.append(x)
        else:
            x = f'year2month{i-12}'
            y.append(x)
    return z

d = zeitraum()
print (d)

输出

How many month? Choose between 1 and 24 
13
{'a string key': ['year1month1', 'year1month2', 'year1month3', 'year1month4', 'year1month5', 'year1month6', 'year1month7', 'year1month8', 'year1month9', 'year1month10', 'year1month11', 'year1month12', 'year2month1']}

有没有更好的编码方法?
编辑:用yevhens、vpfb和zwers的评论,我重写了代码:

def zeitraum():

    while True:
        x = input("How many month? Choose between 1 and 24 \n")
        if 1 <= int(x) <= 24:
            break
        else:
            print ("Wrong input! \n")

    return {'a key': [f"year{m//12+1}month{m%12+1}" for m in range(int(x))]}
niknxzdl

niknxzdl1#

我只是发布核心
这适用于任何正整数 x :

return {'a key': [f"year{m//12+1}month{m%12+1}" for m in range(x)]}
z9zf31ra

z9zf31ra2#

通过一次性生成整个列表,您可以大大简化此过程,例如:

def zeitraum():
    x = input("How many months? Choose between 1 and 24 \n")
    y = ['year{}month{}'.format(m // 12 + 1, m % 12 + 1) for m in range(int(x))]
    z = {'a string key': y}
    return z

你甚至不需要把它限制在24个月,整数除法加12总是返回年数,模加12总是给出一年中的确切月份。

相关问题