Reputation: 161
I have a huge list which looks as follows:
[ '0', '21', '51', '67', '96', '102', '128', '130', '0', '11', '36', '53', '81', '86', '113', 116', '0', '21', '48', '64', '91', '95','125', '139', '166', '175', '200', '205']
I have to carry out simple subtraction over the elements of the list such that:
//Consider 2 variables a & b//
a should store the difference between 0-21 (it should be 21-0 to avoid negative values)
then
b should store the difference between 21-51 (it should be 51-21 to avoid negative values)
then again
a should store the difference between 51-67 (it should be 67-51 to avoid negative values)
and then
b = 67-96
a = 96-102
b = 102-128
a = 128-130
There should be no subtraction between 130
and the following 0
. The new iteration should begin from 0-11,11-36
and so on till the next 0
is encountered.
I am completely out of ideas as to how do i proceed with this step.
Upvotes: 1
Views: 323
Reputation:
As long as the list contains an even number of elements this will work:
# original list
l = ['0', '21', '51', '67', '96', '102', '128', '130']
# convert items in list to integers
l = map(lambda x: int(x), l)
# split the list in two, even indices in p, odd indices in q
p = l[::2]
q = l[1::2]
# print out the calculations
for n in range(len(p)):
print 'abs(%s - %s) = %s' % (p[n], q[n], abs(p[n]-q[n]))
It prints out like so:
abs(0 - 21) = 21
abs(51 - 67) = 16
abs(96 - 102) = 6
abs(128 - 130) = 2
If you are unaware of what slice copies do in the above code, check this out:
>>> l[::2]
['0', '51', '96', '128']
>>> l[1::2]
['21', '67', '102', '130']
The syntax is like so list_name[starting_point:ending_point:increment_by]
.
Upvotes: 1
Reputation: 748
li = [ 0, '21', '51', '67', '96', '102', '128', '130', '0', '11', '36', '53', '81', '86', '113', '116', '0', '21', '48', '64', '91', '95','125', '139', '166', '175', '200', 205]
li = [(int(li[i]),int(li[i+1])) for i in range( len( li ) - 1 ) if li[i+1] != '0']
for a, b in li:
x = abs(a - b)
print '|%3d - %3d| = %3d' % (a,b,x)
Upvotes: 0
Reputation: 40773
Your description of the problem is still unclear, from what I understand, this might be what you are looking for:
li = [ 0, '21', '51', '67', '96', '102', '128', '130', '0', '11', '36', '53', '81', '86', '113', '116', '0', '21', '48', '64', '91', '95','125', '139', '166', '175', '200', 205]
# Convert all items to integers for calculations
li = [int(x) for x in li]
for x, y in zip(li, li[1:]):
if y != 0:
a = abs(x - y)
print '|%3d - %3d| = %3d' % (x, y, a)
else:
print ''
Output:
| 0 - 21| = 21
| 21 - 51| = 30
| 51 - 67| = 16
| 67 - 96| = 29
| 96 - 102| = 6
|102 - 128| = 26
|128 - 130| = 2
| 0 - 11| = 11
| 11 - 36| = 25
| 36 - 53| = 17
| 53 - 81| = 28
| 81 - 86| = 5
| 86 - 113| = 27
|113 - 116| = 3
| 0 - 21| = 21
| 21 - 48| = 27
| 48 - 64| = 16
| 64 - 91| = 27
| 91 - 95| = 4
| 95 - 125| = 30
|125 - 139| = 14
|139 - 166| = 27
|166 - 175| = 9
|175 - 200| = 25
|200 - 205| = 5
Upvotes: 1