[Python] Understand List Comprehensions in Python

List comprehensions provide a concise way to create new lists, where each item is the result of an operation applied to each member of an existing list, dictionary or other iterable. Learn how to create your own list comprehensions in this lesson.

sales = [3.14, 7.99, 10.99, 0.99, 1.24]

sales = [sale * 1.07 for sale in sales]

With condiion:

zoo_animals = ['giraffe', 'monkey', 'elephant', 'lion', 'bear', 'pig', 'horse', 'aardvark']
my_animals = ['monkey', 'bear', 'pig']

other_animals = [animal for animal in zoo_animals if animal not in my_animals]

Recommended way to do:

other_animals = [
 animal
 for animal in zoo_animals
 if animal not in other_animals
]

Break down to multi lines make things looks more clear

原文地址:https://www.cnblogs.com/Answer1215/p/8018759.html