我编写了以下函数。输出值应作为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))]}
2条答案
按热度按时间niknxzdl1#
我只是发布核心
这适用于任何正整数
x
:z9zf31ra2#
通过一次性生成整个列表,您可以大大简化此过程,例如:
你甚至不需要把它限制在24个月,整数除法加12总是返回年数,模加12总是给出一年中的确切月份。