For the list k1=[31.0, 72, 105.0, 581.5, 0, 0, 0], I would like to add a constant for example 100 to the first non-zero element in the reverse list. this is what I want: newk1=[0, 0, 0, 681.5, 105, 72, 31] As a beginner in Python I could not figure it out. Could you please help me. That is my code:
k1=[31.0, 72, 105.0, 581.5, 0, 0, 0]
Inverselist=[]
for i in range(len(etack1)):
Inverselist.append(etack1[-(i+1)])
print("Inverselist", Inverselist)
newk1=Inverselist
run_once = 0
while run_once < 1:
for j in range(len(newk1)):
if newk1[j-1]>0:
newk1[j-1]=newk1[j-1]+100
run_once = 1
break
print("Newk1", newk1 )
The best way to reverse a list using slicing in Python is to use negative indexing. This allows you to step over a list using -1, by using the code list[::-1] .
Using reversed() we can reverse the list and a list_reverseiterator object is created, from which we can create a list using list() type casting. Or, we can also use list. reverse() function to reverse list in-place.
To reverse a string, we simply create a slice that starts with the length of the string, and ends at index 0. The slice statement means start at string length, end at position 0, move with the step -1 (or one step backward).
The reverse() method reverses the sorting order of the elements.
I think you're overthinking this:
First, reverse the list:
inverselist = k1[::-1]
Then, replace the first nonzero element:
for i, item in enumerate(inverselist):
if item:
inverselist[i] += 100
break
Just a silly way. Modifies the list instead of creating a new one.
k1.reverse()
k1[list(map(bool, k1)).index(1)] += 100
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With