我有两个清单。 list1[4,3,2,5,6,0,0,1]
和list2[1,2,5,0,7,0,1,8]
。我必须检查list1
的百分比变化。如果百分比增长为正,则将其标记为1
。
我的代码是:
percent_growth = []
target = []
for i in range(0,len(list1)):
if list1[i] == 0:
percent_growth.append(-9999)
target.append(0)
continue
growth = (list2[i]-list1[i])/list1[i]
percent_growth.append(growth*100)
if growth > 0:
target.append(1)
else:
target.append(0)
但是我的输出是:
percent_growth:[-9999,-9999]
答案 0 :(得分:-1)
代码的问题是,当您迭代list1时检查0 正在运行一个继续默认值-9999和0。 以下代码后继续代码应该在if条件之外。
growth = (list2[i]-list1[i])/list1[i]
percent_growth.append(growth*100)
if growth > 0:
target.append(1)
else:
target.append(0)
您可以使用列表理解。 压缩两个列表
a=[4,3,2,5,6,0,0,1]
b=[1,2,5,0,7,0,1,8]
zip(a,b)创建两个列表的元组。然后使用列表理解来实现。
per_growth = [-9999 if x == 0 else (((y - x) * 100) / x) for x, y in zip(a, b) ]
target = [ 1 if t > 0 else 0 for t in per_growth ]
print([(x,y) for x,y in zip(per_growth, target)])
答案:
[(-75.0, 0), (-33.333333333333336, 0), (150.0, 1), (-100.0, 0), (16.666666666666668, 1), (-9999, 0), (-9999, 0), (700.0, 1)]
根据评论编辑的答案。谢谢。