初学者编码器!我正在寻找一个循环来检查名为" budget"看它是否为负,如果是,它将使用"年" list将年份添加到名为" nodef"的列表中。我的最终结果是列表" nodef"包含所有没有赤字的年份。
budget = [-1075,1225,4239,6084,1489,4031,1846,600,-6409,-19262,-14011,-12969,-9220,-10453,-10315,-3500,-1500,600,600,900]
years = [2000,2001,2002,2003,2004,2005,2006,2007,2008,2009,2010,2011,2012,2013,2014,2015,2016,2017,2018,2019]
nodef = []
i = 0
if i <21:
if budget[i]<0:
nodef.append(years[i])
i += 1
else:
print(nodef)
这就是我现在所拥有的。请告诉我如何批准此事。这完全是出于我自己的好奇心。
答案 0 :(得分:0)
budgets = [-1075,1225,4239,6084,1489,4031,1846,600,-6409,-19262,-14011,-12969,-9220,-10453,-10315,-3500,-1500,600,600,900]
years = [2000,2001,2002,2003,2004,2005,2006,2007,2008,2009,2010,2011,2012,2013,2014,2015,2016,2017,2018,2019]
nodef = []
for budget, year in zip(budgets, years):
if budget < 0:
nodef.append(year)
print(nodef)
答案 1 :(得分:0)
如果要将输出限制为21,可以这样做:
nodef = [year for budget, year in zip(budgets, years) if budget < 0][:21]
如果你真的不需要它,请忽略[:21]
。
另一种方法:
nodef = [years[i] for i, budget in enumerate(budgets) if budget < 0]
答案 2 :(得分:0)
另一种方法是:
nodef = list(map(lambda k: years[k], filter(lambda i: budget[i]<0, range(len(budget)))))
print(nodef)
它产生以下输出:
[2000, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016]