Raymond Feng
Raymond Feng

Reputation: 3

How to select part of a list based on certain conditions

I want to do the following:

L = [(1,2),(3,4),(5,6)]
new_list = list( element in L for i,j in L if i >1 and j >4)

the result of new_list will be [(5,6)]

I know how to do this for 1-d list, for instance:

L1 = [1,2,3,4]

new_L1 = list( i for i in L1 if i>1 )

But I don't know how to do the similar for multi-dimensional lists in python.

Upvotes: 0

Views: 61

Answers (2)

Martijn Pieters
Martijn Pieters

Reputation: 1124818

You can just unpack your nested tuples into your desired variables in the main loop:

[(i, j) for i, j in L if i > 1 and j > 4]

Note that you then do have to 'reconstruct' the original tuple in the left-hand-side expression.

Alternatively, address the elements with indices:

[elem for elem in L if elem[0] > 1 and elem[1] > 4]

Note that I used a list comprehension here (you were using a generator expression inside the list() function, getting you similar results but in a less efficient manner).

Upvotes: 1

Lawrence Benson
Lawrence Benson

Reputation: 1406

you can iterate over the tuples normally:

new_l = [tup for tup in L if tup[0] > 1 and tup[1] > 4]

Upvotes: 1

Related Questions