如何计算列表中的数字 [英] How to calculate numbers in a list

查看:143
本文介绍了如何计算列表中的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码.

A = [86.14803712, 85.25496701, 86.50334271, 86.0266668,  86.61455594, 86.90445213, 86.65519315, 87.10116762, 87.08173861]
B = []
i = 0
for i in range(len(A)):
    c = A[i]-A[i-1]
    B.append(c)
    print(c)

我想获取此列表中两个连续数字之间的差,例如(85.25496701-86.14803712).所以在结果中,我应该有八个数字作为结果.

I want to get the differences between two continuous numbers in this list, eg,(85.25496701-86.14803712). So in the results, I should have eight numbers as results.

但是我得到的结果是:

-0.9337014900000042
-0.8930701099999965 
1.2483756999999969
-0.4766759099999973
0.5878891400000015
0.2898961899999932
-0.24925897999999336
0.4459744699999959
-0.019429009999996083

我不需要-0.9337014900000042,因为它来自第一个数字减去列表中的最后一个数字.我该怎么办呢?谢谢

I don't need -0.9337014900000042 since it comes from the first number subtract the last number in the list. What should I do the fix it? Thanks

推荐答案

这就是python的强项和弱项:当列表不为空时,索引-1始终有效,这可能导致程序不会崩溃但不会崩溃做你想做的事.

That's the strength and the weakness of python: index -1 is always valid when the list isn't empty, which can lead to programs not crashing but not doing what you want.

对于这些操作,最好使用zip使列表与本身的切片版本交织而没有第一个数字:

For those operations, it's better to use zip to interleave the list with a sliced version of itself without the first number:

A = [86.14803712, 85.25496701, 86.50334271, 86.0266668,  86.61455594, 86.90445213, 86.65519315, 87.10116762, 87.08173861]

diffs = [ac-ap for ac,ap in zip(A[1:],A)]

或使用itertools.islice以避免创建新列表以对其进行迭代:

or with itertools.islice to avoid creating a new list to iterate on it:

import itertools
diffs = [ac-ap for ac,ap in zip(itertools.islice(A,1,None),A)]

结果(8个值):

[-0.8930701099999965, 1.2483756999999969, -0.4766759099999973, 0.5878891400000015, 0.2898961899999932, -0.24925897999999336, 0.4459744699999959, -0.019429009999996083]

这篇关于如何计算列表中的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆