首页 > 解决方案 > 计算两个列表中的百分比变化

问题描述

我有两个清单。list1[4,3,2,5,6,0,0,1]list2[1,2,5,0,7,0,1,8]。我必须检查百分比变化wrt 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]

标签: pythonlist

解决方案


您的代码的问题是,在迭代时,您正在检查 list1 中的 0,您正在运行 continue 默认值为 -9999 和 0。以下代码后 continue 应该在 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)]

根据评论编辑答案。谢谢。


推荐阅读