python - How do i perform operations between elements of a lists in Python using indecies?
问题描述
I have a list of values like this one:
L = [2, 5, 6, 8, 10, 13]
I want to calculate the difference between the first two values and store it into a list using the list indexes. Then, calculate the difference between the second and the third and so on...
I tried a loop like this without success:
[(L[i+1] - L[i]) for i in L]
解决方案
在您的循环中,i
保存值,而不是索引,迭代range(len(L))
以获取索引(实际上range(len(L) - 1)
因为您正在获取下一个值):
>>> [(L[i + 1] - L[i]) for i in range(len(L) - 1)]
[3, 1, 2, 2, 3]
在这种情况下,zip
也可以派上用场(在此处迭代值):
>>> [y - x for x, y in zip(L, L[1:])]
[3, 1, 2, 2, 3]
推荐阅读
- php - Zoho API-V2 添加 Attactmetn URL
- c# - GetString(IStringLocalizer, String, Object[]) returns null when Unit-Testing
- webpack - Webpack 在浏览器中加载原生 ES6 模块并绑定后备
- node.js - How to correctly make multiple MySQL calls in a single request with Node.js, Express.js, MySQL2, and Promises
- web-component - A-Frame Web 组件兼容性
- java - Use the Mysql ClusterJ jar file to connect to NDB cluster
- r - R中的动态列名
- python - 在 Pycharm Python 代码中找不到模块“Pandas”和“Numpy”
- gdb - GDB 打印整个指针树
- three.js - Can I create point cloud from depth and rgb image?