List generation basic syntax
1. Use list generation , A line to solve for loop
2. Double loop
3. Add judgment statement , filter
4. Add functions
5. Several iterators are common :range、 zip 、 enumerate 、 filter 、 reduce
List generation basic syntax[exp for iter_var in iterable (if conditional)]
principle :
First iteration iterable Everything in the , Every iteration , All the iterable The corresponding contents in iter_var in , Then put the expression exp Apply the iter_var The content of , Filter according to the conditions
Last use The evaluated value of the expression Generate a new list
Prior to the for and if loop :
1、 Than for The cycle is much faster
2、 It is considered to have more python characteristic
3、 List generation syntax is easier to read
1. Use list generation , A line to solve for loop# Realization [1,2,3,4,5] A list of alist1 = list(range(1,6))print(alist1)# Realization [1,4,9,16,25,36,49] A list of alist2 = []for i in range(1,8): alist2.append(i*i)print(alist2)# One line implementation alist = [i*i for i in range(1,8)]print(alist)# result :[1, 2, 3, 4, 5][1, 4, 9, 16, 25, 36, 49][1, 4, 9, 16, 25, 36, 49]
2. Double loop list2 = [x+y for x in range(1,5) for y in range(1,6)]# result :[2, 3, 4, 5, 6, 3, 4, 5, 6, 7, 4, 5, 6, 7, 8, 5, 6, 7, 8, 9]
3. Add judgment statement , filter list3 = [x for x in range(1,10) if x>5]print(list3)# result :[6, 7, 8, 9]
4. Add functions L = ['Heli','JACK','ab']l1 = [i.lower() for i in L]print(l1)# result :['heli', 'jack', 'ab']
5. Several iterators are common :range、 zip 、 enumerate 、 filter 、 reducezip Generate list , Generate Dictionary
zip() The function takes a series of iteratable objects as arguments , Package the corresponding elements in different objects into a tuple (tuple), Returns the... Composed of these tuples list list
l1 = [1,3,6]l2 = [5,8,9]for (x,y) in zip(l1,l2): print(x,y,x+y)# result :1 5 63 8 116 9 15keys = ['a','c','f']vals = [1,7,3]D2 = {}for (k,v) in zip(keys,vals): D2[k]=vprint(D2)# result :{'a': 1, 'c': 7, 'f': 3}
enumerate() Function is used to traverse a data object ( As listing 、 Tuples or strings ) Combined into an index sequence , List both data and data index , Generally used in for In circulation
enumerate(seq, [start=0]) , Return enumeration object
seasons = ['spring', 'summer', 'winter']a = list(enumerate(seasons))for i,element in enumerate(seasons): print(i,element)# result :0 spring1 summer2 winter
About filter 、 reduce, See the previous article for details
python Tutorial examples for using higher-order functions
That's all python List generator common iterator example details , More about python For information about list generator iterators, please pay attention to other related articles on the software development network !