Reputation: 11
I'm trying to combine certain elements in a list if they are of a specific value with its righter-neighbouring element.
(The specific value in this case being a minus sign).
Say I have the following list:
x = ['0', '0', '8', '-', '6', '4', '0', '5', '1', '2', '1', '2', '-', '5']
What can I do to the list so that It'll look like this?:
x = ['0', '0', '8', '-6', '4', '0', '5', '1', '2', '1', '2', '-5']
I basically need every instance of the element '-' to be paired with the next element (of which the index is +1 of the index of the minus sign). Sorry if this is quite vague, I'm still quite new to python and as such my terminology may be lacking.
Upvotes: 0
Views: 33
Reputation: 2882
neg = False
out = []
for i in x:
if i == '-':
neg = True
else:
if neg:
out += ['-' + i]
neg = False
else:
out += [i]
In [18]: out
Out[18]: ['0', '0', '8', '-6', '4', '0', '5', '1', '2', '1', '2', '-5']
In the code above, there is flag neg
which indicates previous item was a minus sign or not (True means it was a minus sign). Then we populate the out
list with the element from x with the rule that if you have -
then set the flag to True
but do nothing. Then if the element is not -
and neg
is True
then append negative of the element and set the flag to False
, but if the flag is False
just append the element.
Upvotes: 1
Reputation: 513
Try this:
x = ['0', '0', '8', '-', '6', '4', '0', '5', '1', '2', '1', '2', '-', '5']
for i in range(len(x)):
if x[i] == '-':
x[i+1] = x[i] + x[i+1]
y = [i for i in x if i != '-']
print(y)
It merges elements, then remove all of minus sign'-'
from list.
Upvotes: 0