Reputation: 43
I have a list in python:
A=[[303 80]
[390 43]
[446 16]
[471 16]
[505 44]
[557 225]
[642 22]
[672 15]
[694 86]
[702 76]]
Now I want to remove the rows A[i]
which have a bigger summary value than the next item in the list.
A[i][0]+A[i][1] > A[i+1][0]
I code this lines:
B=[]
for i in range(len(A)-1):
if A[i][0]+A[i][1]<=A[i+1][0]:
B.append(A[i])
B.append(A[i+1])
I got this result:
B=[[303 80]
[390 43]
[446 16]
[471 16]
[505 44]
[642 22]
[672 15]
[702 76]]
Are there any other ways which are shorter and quicker than this. Thank you very much.
Upvotes: 0
Views: 98
Reputation: 12015
[a for a,b in zip(A, A[1:]) if sum(a)<=b[0]] + [A[-1]]
or
[a for i,a in enumerate(A[:-1]) if sum(a)<=A[i+1][0]] + [A[-1]]
Upvotes: 2
Reputation: 27201
Iterate through a zip
of (current, next) items.
def filt(A):
def cond(a, b):
return a[0] + a[1] <= b[0]
return [a for a, b in zip(A, A[1:]) if cond(a, b)] + [A[-1]]
You might even consider itertools
, or better, numpy
if performance is an issue.
NOTE: This solution falls for the problems I discussed in a comment above.
As @smci mentions, doing this naively like this might give you something you weren't expecting.
filt(A)
is not the same asfilt(filt(A))
for all possible inputsA
.
Upvotes: 2
Reputation: 1190
Try:
B=[d for c,d in enumerate(A) if c < len(A)-1 and A[c][0]+A[c][1] <= A[c+1][0]]
B.append(A[-1])
Upvotes: 0
Reputation: 5414
You can use list comprehension
for an one-liner solution.
Without last element (because last element has no next element to compare):
expected_list = [A[i] for i in range(len(A)-1) if A[i][0] + A[i][1] <= A[i + 1][0]]
With Last element (your expected output):
expected_list = [A[i] for i in range(len(A)) if i==len(A)-1 or A[i][0] + A[i][1] <= A[i + 1][0]]
Upvotes: 0