leo
leo

Reputation: 1117

Python list compreehension with restrictions

I have a list of tuples like this (but much bigger):

t = [(1, 2, 3), (4, 5, 6)]

I want a list with all the first elements of each tuple. I have:

first = list(x[0] for x in t)

Suppose I only want to add to 'first' a number if it's smaller than EPS. What I want is something like:

first = list(x[0] for x in t, x[0] < EPS)

But this is not a valid python statement.

I'd like to know what's the pythonic way of doing this (I can do it in the same way I'd do it in Java/C++, but I imagine there must be a better way.

Upvotes: 1

Views: 397

Answers (1)

user268396
user268396

Reputation: 12006

Use:

[x[0] for x in t if x[0] < EPS]

Upvotes: 5

Related Questions