如何使for循环不跳过列表中的最后两个元素?

时间:2021-04-12 15:56:40

标签: python list

我试图从列表中的第一个较低值中减去列表中的每个元素,即使元素的较低值不在下一个索引中 例如,我有列表 [7,18,5,5,20,9,14,21,19] 它应该产生 [2,13,5,5,11,9,14,2,19]

   for i in range(len(numeric_list)-2):  
     if numeric_list[i] >numeric_list[i+1]:
         msg[i] = numeric_list[i] - numeric_list[i+1]  
     elif numeric_list [i]<numeric_list[i+1] and numeric_list[i]>numeric_list[i+2]   :
         msg[i]= numeric_list[i]-numeric_list[i+2]
     else :
         msg[i]=numeric_list[i]

我使用了这段代码,但是 for 循环跳过了列表的最后两个元素,我尝试更改循环的范围,但由于 elif 语句,它给了我“列表超出范围”

2 个答案:

答案 0 :(得分:0)

我修改了代码并插入了一些注释。希望,它有帮助 -


list1 =  [ 7,18,5,5,20,9,14,21,19]
result= []
for index,i in enumerate(list1): # enumerate will provide index value which can be used for list slicing later
    k=0 # flag this will check if the smaller number is available or not
    for j in list1[index+1:]: # we need to take only those list items which comes after the element
        if j < i :
            result.append(i-j) # if number is found change the value of k and break the loop
            k=1
            break
    if k ==0: # if the smaller number is not found don't change the value and insert the same number. 
        result.append(i)
print(result)

答案 1 :(得分:-2)

以下是针对您的问题的更简短的解决方案(逐行):

list1 = [7, 18, 5, 5, 20, 9, 14, 21, 19]

result = [number - [value if value < number else 0 for value in list1[index + 1 if index + 1 < len(list1) else index:]][0] for index, number in enumerate(list1)]
print(result)

基本上它是一个复杂的列表理解(从来没有做过这么复杂的事情)但它有效

相关问题