查找列表中连续数字之间的差异(Python) [英] Finding the difference between consecutive numbers in a list (Python)
问题描述
给出一个数字列表,我试图编写一个代码,该代码查找连续元素之间的差异.例如,A = [1, 10, 100, 50, 40]
,因此函数的输出应为[0, 9, 90, 50, 10]
.到目前为止,这是我尝试使用递归的方法:
Given a list of numbers, I am trying to write a code that finds the difference between consecutive elements. For instance, A = [1, 10, 100, 50, 40]
so the output of the function should be [0, 9, 90, 50, 10]
. Here is what I have so far trying to use recursion:
def deviation(A):
if len(A) < 2:
return
else:
return [abs(A[0]-A[1])] + [deviation(A[1: ])]
但是,我得到的输出(使用上述A的示例作为输入)是[9, [90, [50, [10, None]]]]
.如何正确格式化方括号? (我已经尝试过猜测和检查,但是我这是我得到的最接近的东西)而且我该如何编写它在从前一个元素中减去当前元素而又没有第一个元素出现索引错误的地方?我仍然希望输出列表的第一个元素为零,但我不知道如何使用递归进行此操作,由于某种原因,这似乎是我的最佳选择.
The output I get, however, (using the above example of A as the input) is [9, [90, [50, [10, None]]]]
. How do I properly format my brackets? (I've tried guessing and checking but I this is the closest I have gotten) And how do I write this where it subtracts the current element from the previous element without getting an index error for the first element? I still want the first element of the output list to be zero but I do not know how to go about this using recursion and for some reason that seems the best route to me.
推荐答案
您可以这样做:
[y-x for x, y in zip(A[:-1], A[1:])]
>>> A = [1, 10, 100, 50, 40]
>>> [y-x for x, y in zip(A[:-1], A[1:])]
[9, 90, -50, -10]
请注意,如果右侧较小,则差异为负,您可以轻松地解决此问题(如果您认为这是错误的话),我将为您保留解决方案.
Note that the difference will be negative if the right side is smaller, you can easily fix this (If you consider this wrong), I'll leave the solution for you.
说明:
您可以获得的最佳解释就是简单地打印列表理解的每个部分.
The best explanation you can get is simply printing each part of the list comprehension.
-
A[:-1]
返回不带最后一个元素的列表:[1, 10, 100, 50]
-
A[1:]
返回不包含第一个元素的列表:[10, 100, 50, 40]
-
zip(A[:-1], A[1:])
返回[(1, 10), (10, 100), (100, 50), (50, 40)]
- 最后一步就是简单地返回每个元组中的差异.
A[:-1]
returns the list without the last element:[1, 10, 100, 50]
A[1:]
returns the list without the first element:[10, 100, 50, 40]
zip(A[:-1], A[1:])
returns[(1, 10), (10, 100), (100, 50), (50, 40)]
- The last step is simply returning the difference in each tuple.
这篇关于查找列表中连续数字之间的差异(Python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!