What I have right now:
a_list = [25, 23, 12, 8, 4 ,2, 1]
new_list = []
for i, num in enumerate(a_list):
new_num = num - num[i 1]
new_list.append(new_num)
print(new_list)
#Error: new_num = num - num[i 1]
TypeError: 'int' object is not subscriptable
#Expected: [2, 11, 4, 2, 1]
CodePudding user response:
zip is appropriate here, instead of enumerate. Simply zip a_list with a_list[1:] (so that you can "see" two consecutive elements) and find differences.
new_list = [i-j for i, j in zip(a_list, a_list[1:])]
The reason enumerate doesn't work with your implementation is that you want to index an integer in a_list by num[i 1] which is nonsensical.
If you absolutely want to use enumerate, one important thing is to ensure that you don't want get an IndexError, i.e. you don't want to index beyond the list. One way to ensure that doesn't happen is to only enumerate until a_list[:-1]. Then make sure you index a_list (and not num) and you're good to go.
new_list = []
for i, num in enumerate(a_list[:-1]):
new_num = num - a_list[i 1]
new_list.append(new_num)
Output:
[2, 11, 4, 4, 2, 1]
CodePudding user response:
You seem to want:
a_list = [25, 23, 12, 8, 4 ,2, 1]
new_list = [a - b for a, b in zip(a_list, a_list[1:])]
print(new_list)
If you use a library like numpy, this is simpler:
import numpy as np
a_arr = np.array([25, 23, 12, 8, 4 ,2, 1])
new_arr = a_arr[:-1] - a_arr[1:]
print(new_arr)
Both solutions do the same thing using slicing, taking the original list and pairing each element with the same list, minus the first element. zip() automatically omits the last element from the first list, since there is no element to pair it with in the second list. numpy wants you to tell it to omit the last element (a_arr[:-1]) so that they have the same size.
CodePudding user response:
You're trying to use indices with num, which is the value at position i in the list, not the list. Iterate over the list with range(a_list)-1, so that you access the numbers at positions i and i 1 directly from the list.
CodePudding user response:
Okay, it's Pretty Simple...What you can do basically just subtract arr[index] - arr[index 1] and append it to a new list and after just print it note range should be (0, old_list.len() - 1)
a_list = [25, 23, 12, 8, 4 ,2, 1] #old list
nw_lst = [] #new list to print and where we will append
size = len(a_list); #Size of the old_list
for i in range(0, size-1):
x = a_list[i] - a_list[i 1] #claculating difference
nw_lst.append(x) #appending the difference to new list
print(nw_lst) #printing new list
OUTPUT:
[2, 11, 4, 4, 2, 1]
