简体   繁体   English

仅当较早的数字小于当前数字时,如何在 python 列表中找到数字的差异

[英]how to find the difference of a number and it's earlier numbers in python list only if the earlier number is less than the current number

I have a list我有一个清单

my_list = [6, 9, 10, 0, 5]

how to write a code to get a list of all the differences of a number from it's earlier number only if it's greater than the earlier number如何编写代码以获取一个数字与其早期数字的所有差异的列表,前提是它大于早期数字

my_list[0] has no earlier number my_list[0]没有更早的编号

my_list[1] = 9 which is greater than my_list[0] we can find the difference 9-6 = 3 . my_list[1] = 9大于my_list[0]我们可以找到差异9-6 = 3 now answer_list=[3] .现在answer_list=[3]

my_list[2] = 10 which is greater than my_list[0] , my_list[1] answer_list = [3, 1, 4] my_list[2] = 10大于my_list[0] , my_list[1] answer_list = [3, 1, 4]

my_list[3] = 0 no previous number is less than 2 . my_list[3] = 0没有前一个数字小于2 Do nothing没做什么

my_list[4] = 5 .我的my_list[4] = 5 my_list[3] is less than my_list[4] . my_list[3]小于my_list[4] answer_list = [3, 1, 4, 5]

should return [3, 1, 4, 5]应该return [3, 1, 4, 5]

my solution is我的解决方案是

def ans(my_list):
    new_list = []
    for x in my_list:
        for i in range(my_list.index(x)):
            if x >= my_list[i]:
                diff = x - my_list[i]
                new_list.append(diff)
    return new_list

is there a better way to this, the nested loops is bit over kill and time consuming有没有更好的方法呢,嵌套循环有点过度杀戮和耗时

You need two loops, but you can drop the need to use index if you use enumerate .您需要两个循环,但如果您使用enumerate ,则可以放弃使用index

my_list = [6, 9, 10, 0, 5]

result = []
for index, value in enumerate(my_list[1:], start=1):
    for previous_value in my_list[:index]:
        difference = value - previous_value
        if difference > 0:
            result.append(difference)

print(result)

Bonus: your algorithm has problems if you have duplicate numbers in the orginal list, like [6, 9, 10, 9, 10, 0, 5] .奖励:如果原始列表中有重复的数字,您的算法就会出现问题,例如[6, 9, 10, 9, 10, 0, 5] This approach takes care of it.这种方法可以解决它。 Your result: [3, 4, 1, 3, 4, 1, 5] , correct result: [3, 4, 1, 3, 4, 1, 1, 5]您的结果: [3, 4, 1, 3, 4, 1, 5] ,正确的结果: [3, 4, 1, 3, 4, 1, 1, 5]


Less nested, but less readable:嵌套较少,但可读性较差:

result = []
for index, value in enumerate(my_list[1:], start=1):
    result.extend(filter(lambda x: x > 0, (value - previous_value for previous_value in my_list[:index])))
print(result)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM