Генерация
списков в Python.
Тема довольно
заезженная, но почему бы не обзавестись
еще одной шпаргалкой?
>>> animal_names = [animal.name for animal in list_of_animals]
>>> squares = [x*x for x in range(15)]
>>> div_by_seven = [x for x in range(100) if x%7 == 0]
>>> moods = ['sad' if person.is_alone() else 'happy' for person in people_at_party]
>>> ident_matrix = [[1 if col_index==row_index else 0 for row_index in range(4)] for col_index in range(4)]
>>> flattened = [num for row in ident_matrix for num in row]
>>> even_zeroes = [num for row in ident_matrix if ident_matrix.index(row)%2==0 for num in row if num==0]
You can see how the
awkward alternations between our assignments and our predicates
quickly make our list comprehension much harder to read and follow.
This is where list comprehensions begin to approach the limit of
their usefulness. As much as it’s nice to have everything on one
line, list comprehensions are meant as a convenience tool; if they’re
making your code more complex and unreadable, they should be replaced
by a more traditional structure. If your code looks indecipherable
and fits on one line but could easily be replaced by a few more lines
that could be written by a coder with only minimal experience with
python, you’re trying too hard to impress someone.
>>> even_zeroes = []
>>> for row in ident_matrix[::2]:
>>> for val in row:
>>> even_zeroes.append(val) if val == 0 else None
Там еще про
словари, про генераторы немножко. Годная
статья.
original post http://vasnake.blogspot.com/2013/01/list-comprehensions.html
original post http://vasnake.blogspot.com/2013/01/list-comprehensions.html
Комментариев нет:
Отправить комментарий