Reputation: 165
x1 = [1, 2, 3, 4, 5, 6]
x2 = [3, 5, 6, 8, 9]
x3 = [2, 4, 5, 7, 13]
x4 = [11, 22, 33, 24, 55, 66]
x5 = [11, 7, 1, 2, 3, 4, 5, 6]
How do I remove the increasing values on every list?
If I removed the increasing in those lists, they should look like this:
x1 = [1, 6]
x2 = [3, 9]
x3 = [2, 13]
x4 = [11, 33, 24, 66]
x5 = [11, 7, 1, 6]
Upvotes: 0
Views: 45
Reputation: 30258
You can use a generator to build up the runs and yield
the results, e.g.:
def runs(iterable):
iterable = iter(iterable)
i = [next(iterable)] # Empty iterable not handled
for j in iterable:
while j and i[-1] < j:
i.append(j)
j = next(iterable, None)
i[1:-1] = [] # Removes the middle of the run, if there is one
yield from i
i = [j]
if j:
yield j
# Using @StephenRauch data set
data = (
[1, 2, 3, 4, 5, 6],
[3, 5, 6, 8, 9],
[2, 4, 5, 7, 13],
[11, 22, 33, 24, 55, 66],
[11, 7, 1, 2, 3, 4, 5, 6]
)
>>> [list(runs(d)) for d in data]
[[1, 6], [3, 9], [2, 13], [11, 33, 24, 66], [11, 7, 1, 6]]
Upvotes: 2
Reputation: 49794
This will remove any increasing elements:
def remove_increasing(a_list):
return [a_list[0]] + \
[y for x, y in zip(a_list, a_list[1:]) if x >= y] + \
[a_list[-1]]
data = (
[1, 2, 3, 4, 5, 6],
[3, 5, 6, 8, 9],
[2, 4, 5, 7, 13],
[11, 22, 33, 24, 55, 66],
[11, 7, 1, 2, 3, 4, 5, 6]
)
for d in data:
print(remove_increasing(d))
[1, 6]
[3, 9]
[2, 13]
[11, 24, 66]
[11, 7, 1, 6]
Upvotes: 1
Reputation: 33335
Your question is unclear. What does "remove the increasing values" mean?
Clearly you don't mean "remove every value that is larger than the previous one", because your example results include the last element which is larger.
But, assuming you know what you mean, here's how to do it:
To delete a value from a list:
mylist.remove(4)
To remove the item at a specific position from a list: (remember that Python lists start at position zero, not position one)
del mylist[2]
Upvotes: 0