python - 计算两个列表中的百分比变化
问题描述
我有两个清单。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]
解决方案
您的代码的问题是,在迭代时,您正在检查 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)]
根据评论编辑答案。谢谢。
推荐阅读
- ios - 如何以编程方式访问 iOS 13 中的应用程序语言?
- google-apps-script - Google Apps 脚本 -- 隐藏“运行脚本”通知
- mysql - SQL 语句运行缓慢
- c# - 从 POST 请求中使用嵌套的 JSON,无法将嵌套的 JSON 分配给我的班级
- keycloak - CAS 6.1 - Pac4J 的状态参数为空
- c - 用另一个指针强制转换的结构指针
- java - 如何在使用并行方法时使 forEach 循环线程中的单个任务安全?
- spring - 尝试在 Spring Boot 2.1 中下载没有扩展名的文件时出现 404
- javascript - 尝试在 Excel API 中锁定或解锁一系列单元格时,为什么会出现 AccessDenied
- vuetify.js - vuetifyjs 表单标签位置