python - 计算列表中相邻余弦值之间的差

标签 python

我想找出值 1 到 10 的余弦函数值的差异。 所以:

import math
import sys
import string
import os

for n in range (1,11): 
        x = math.cos (n)
        print x

这个简单的脚本打印 n = 1 到 10 的余弦值现在我需要确定各个值之间的差异,并从 n = 2 的值中获取它并从 n = 1 的值中读取值然后获取该值对于 n = 3 和 n = 2 所以:

Math.cos (2) - Math.cos (1)

Math.cos (3) - Math.cos (2)

Math.cos (4) - Math.cos (3)

.

.

Math.cos (10) - Math.cos (9)

最后

Math.cos (10) - Math.cos (1)

然后我想将这些值相加...但我可能已经放在一起了

最佳答案

我可能会做这样的事情:

for x,y in zip(range(2,11)+[10],range(1,10)+[1]):
    print math.cos(x) - math.cos(y)

当然,这只适用于 python2.x,其中 range 返回一个列表。为了解决这个问题,您可以使用itertools.chain。即:range(2,11)+[10] 变为chain(range(2,11),[10])。这里要学习的关键函数是zip

关于python - 计算列表中相邻余弦值之间的差,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14714466/

相关文章:

python - 用 Python 3 编写 Cocoa 应用程序

python - 两个读取和附加程序在同一个文本文件上给出无法识别的输出

python - 确保 numpy 数组中至少有一定的维度

python - 从 numPy 数组列表中删除重复项

python - 嵌套列表循环

python - BeautifulSoup 从 Indeed 提取数据时出现问题

python - or-tool python 中的变量除法

python - tqdm:更新总数不重置时间已过

python - 使用字典中的键从数据帧中检索值

Python Beautiful Soup WebScraping : Return only new data?