|
Original |
Translation |
|
45
|
# Given the list L, make a list of all strings # containing the substring S. sublist = filter( lambda s, substring=S: string.find(s, substring) != -1, L)
|
|
|
46
|
Because of Python's scoping rules, a default argument is used so that the anonymous function created by the :keyword:`lambda` statement knows what substring is being searched for. List comprehensions make this cleaner::
|
|
|
47
|
sublist = [ s for s in L if string.find(s, S) != -1 ]
|
|
|
48
|
List comprehensions have the form::
|
|
|
49
|
[ expression for expr in sequence1 for expr2 in sequence2 ... for exprN in sequenceN if condition ]
|
|
|
50
|
|
51
|
To make the semantics very clear, a list comprehension is equivalent to the following Python code::
|
|
|
52
|
for expr1 in sequence1: for expr2 in sequence2: ... for exprN in sequenceN: if (condition): # Append the value of # the expression to the # resulting list.
|
|
|
53
|
This means that when there are multiple :keyword:`for`...\ :keyword:`in` clauses, the resulting list will be equal to the product of the lengths of all the sequences. If you have two lists of length 3, the output list is 9 elements long::
|
|
|
54
|
seq1 = 'abc' seq2 = (1,2,3) >>> [ (x,y) for x in seq1 for y in seq2] [('a', 1), ('a', 2), ('a', 3), ('b', 1), ('b', 2), ('b', 3), ('c', 1), ('c', 2), ('c', 3)]
|
|