1

I have created a list where within it I seek to eliminate only the lists whose first value is greater than the second value of it.

I tried creating a second list with the elements to remove but I think it is not the most optimal way.

#y = [] x = [[1, 4], [1, 6], [2, 5], [2, 7], [4, 8], [6, 5], [6, 7], [2, 6], [3, 7], [5, 8], [6, 4], [7, 5]] for i in range(len(x)): if x[i][0] > x[i][1]: print(x[i]) # y.append(x[i]) 

Is there an optimal way to achieve this?

I want that when printing on screen you get the following:

[[1, 4], [1, 6], [2, 5], [2, 7], [4, 8], [6, 7], [2, 6], [3, 7], [ 5, 8]] 

Best regards,

4 Answers 4

4

This should work:

y = [[a,b] for a,b in x if a <= b] 

Testing:

>>> x = [[1, 4], [1, 6], [2, 5], [2, 7], [4, 8], [6, 5], [6, 7], [2, 6], [3, 7], [5, 8], [6, 4], [7, 5]] >>> y = [[a,b] for a,b in x if a < b] >>> y [[1, 4], [1, 6], [2, 5], [2, 7], [4, 8], [6, 7], [2, 6], [3, 7], [5, 8]] >>> 
Sign up to request clarification or add additional context in comments.

2 Comments

Should it be if a <= b?
@JoshuaHall maybe, OP did not say anything about that, but you're right, I made the change =)
0

This modifies the original list:

for i, (a, b) in enumerate(x): if a > b: del x[i] 

Comments

0

Creating a new list:

[v for v in x if v[0] <= v[1]] 

Or elimination in place:

for i in range(len(x) - 1, -1, -1): # need to start at the end if x[i][0] > x[i][1]: x.pop(i) 

Comments

0
>>> filtered = list(filter(lambda f: f[0] < f[1], x)) >>> print(filtered) 

This will create a new list with the desired values, using the built in filter(function, iterable) function.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.