Accounting list without 'for'

Often when working with lists in Python, I end up just want to filter out the elements from the list.

numbers = [5, 1, 4, 2, 7, 4]
big_nums = [num for num in numbers if num > 2]

It seems to me too detailed. I have to define and use num in two separate ( num for num ...) statements , although I do not perform any operations with num.

I tried [num in numbers if num > 2], but python throws away SyntaxErrorwith this.

Is there a shorter way to do this in Python?

Edit:

My question is is there a better way to do what I'm trying to do in Python. There are many times when in Python, which I did not know about, there was a construction, but which made my code more understandable and understandable.

I am not asking about compromising performance between filterand understanding the list. I have no problem understanding lists, but I also had no problems compiling lists with standard loops forbefore I learned about list comprehension.

+4
source share
1 answer

Well, you can use it filter, it is slower and not readable, but you do not need for:

list(filter(lambda x: x > 2, numbers))

or

list(filter((2).__lt__, numbers))

However, using magical methods like this is fragile, it will only work if the list contains only integers. As Chris_Rands noted, you usually use operator.ltinstead:

from functools import partial
from operator import lt
list(filter(partial(lt, 2), numbers))

This also works if the list contains other numeric types than int.

+8
source

Source: https://habr.com/ru/post/1686652/


All Articles