List derivation list comprehension
Generator Expressions generator expression
notes : Except for the change of square brackets , The generator expression does not return a list . The generator expression returns the generator object , It can be used as for Iterators in loops .
example Change a string into Unicode Code point list
>>> symbols = '[email protected]#$%^&*abc'
>>> codes = [ord(symbol) for symbol in symbols]
>>> codes
[33, 64, 35, 36, 37, 94, 38, 42, 97, 98, 99]
>>>
Usage principle : Just list derivation to create a new list , And try to keep it short ( If it exceeds two lines, consider using for Loop rewrite )
explain :Python Will ignore the code []、{} and () Line breaks in , So if you have a multi line list in your code 、 The list of deduction 、 Generator Expressions 、 Dictionaries and the like , You can omit the line continuation characters that are not very good-looking \.
------------------------------------------------------
example Use list derivation to calculate Cartesian product
>>> colors = ['black', 'white']
>>> sizes = ['S', 'M', 'L']
>>> tshirts = [(color, size) for color in colors for size in sizes]
>>> tshirts
[('black', 'S'), ('black', 'M'), ('black', 'L'), ('white', 'S'), ('white', 'M'), ('white', 'L')]
>>>
above for color in colors for size in sizes The colors have been arranged first , Then arrange by size , Equivalent to for A nested loop
>>> for color in colors:
... for size in sizes:
... print((color, size))
...
('black', 'S')
('black', 'M')
('black', 'L')
('white', 'S')
('white', 'M')
('white', 'L')
>>>
------------------------------------------------------
example Initialize tuples with generator expressions
>>> symbols = '[email protected]#$%^&*abc'
>>>
>>> tuple(ord(symbol) for symbol in symbols)
(33, 64, 35, 36, 37, 94, 38, 42, 97, 98, 99)
>>>
>>> list(ord(symbol) for symbol in symbols)
[33, 64, 35, 36, 37, 94, 38, 42, 97, 98, 99]
>>>
>>> set(ord(symbol) for symbol in symbols)
{64, 33, 97, 35, 36, 37, 38, 98, 99, 42, 94}
>>>
------------------------------------------------------
example Use the generator expression to calculate the Cartesian product
>>> colors = ['black', 'white']
>>> sizes = ['S', 'M', 'L']
>>> ('%s %s'%(c, s) for c in colors for s in sizes)
>>> for tshirt in ('%s %s'%(c, s) for c in colors for s in sizes):
... print(tshirt)
...
black S
black M
black L
white S
white M
white L
>>>
Reference books :《 smooth Python》2.2 List derivations and generator expressions