Python's generative style can write very elegant code when some types convert to each other. If the list is converted to another list, dictionary, or tuple. and the execution of code is more efficient than using for...in ... High cycle.
List-generated
List generation is generated by generating lists, which are simple and elegant, and can be fused into one line with multiple lines of code. The main purpose is to convert other objects into lists or filter the original list.
#List Conversion Listls = [1,2,4,6]LS1= [x**2 forXinchLS]Print(LS1) results: [1,4,16,36]#Filter on List, returns true to the listls = [1,2,4,6]LS1= [x**2 forXinchLsifX > 3]Print(LS1) results: [16, 36]#multi-Conditional filteringls = [1,2,4,6]LS1= [x**2ifX > 2ElseX**3 forXinchLS]Print(LS1) results: [1, 8, 16, 36]#Multiple Loopsls = [1,2,4,6]LS1= [X**yifX > 2ElseX**3 forXinchLs forYinchLS]Print(LS1) results: [1, 1, 1, 1, 8, 8, 8, 8, 4, 16, 256, 4096, 6, 36, 1296, 46656]
Generator-generated
- Using a generator Instead of a list can reduce memory consumption when it comes to manipulating a value that needs to traverse a list rather than a list.
ls = [1,2,4,6]LS1= (x**2 forXinchls)Print(LS1) Results:<generator Object <genexpr> at 0x0000021b21ded150>#through for: In fetching data does not need to process stopiteration forIinchLS1:Pass#Next () method requires processing Stopiteration whileTrue:Try: Print(Next (LS1))exceptstopiteration:Pass
Dictionary-generated
Dictionary generation You can write very elegant code when you need to convert a list or tuple into a dictionary.
#Dict () can accept the notation of similar list generation, if LS is at least two-dimensional iterative object, otherwise errorls = [('name1','Xiao'),('name2','Wang')]dict_ls= Dict (x forXinchls)Print(Dict_ls) Result: {'name1':'Xiao','name2':'Wang'}
Tuple-generated
Since () This form of similar list generation is occupied by the generator, all tuple generation uses tuple ().
ls = [('name1',['1','2']),('name2','Wang')]dict_ls= Tuple (x forXinchls)Print(Dict_ls) Results: ('name1', ['1','2']), ('name2','Wang'))
Python dictionary, list, tuple builder usage