程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

[python] list derivation and generator expression

編輯:Python

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


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved