[英]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
我有一个清单
my_list = [6, 9, 10, 0, 5]
如何编写代码以获取一个数字与其早期数字的所有差异的列表,前提是它大于早期数字
my_list[0]
没有更早的编号
my_list[1] = 9
大于my_list[0]
我们可以找到差异9-6 = 3
。 现在answer_list=[3]
。
my_list[2] = 10
大于my_list[0]
, my_list[1]
answer_list = [3, 1, 4]
my_list[3] = 0
没有前一个数字小于2
。 没做什么
我的my_list[4] = 5
。 my_list[3]
小于my_list[4]
。 answer_list = [3, 1, 4, 5]
应该return [3, 1, 4, 5]
我的解决方案是
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
有没有更好的方法呢,嵌套循环有点过度杀戮和耗时
您需要两个循环,但如果您使用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)
奖励:如果原始列表中有重复的数字,您的算法就会出现问题,例如[6, 9, 10, 9, 10, 0, 5]
。 这种方法可以解决它。 您的结果: [3, 4, 1, 3, 4, 1, 5]
,正确的结果: [3, 4, 1, 3, 4, 1, 1, 5]
嵌套较少,但可读性较差:
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.