1.1 List-generated
Python's built-in , very simple but powerful build that can be used to create lists .
to generate [1x1, 2x2, 3x3, ..., 10x10] What to do
>>> L = []
>>> for I in range (1, 6):-- Loop
... L.append (i * i)
...
>>> L
[1, 4, 9, 16, 25]
>>> [x * xfor x in range (1, 6)] -- list Generation
[1, 4, 9, 16, 25]
X * x the element to be generated is placed in front and can be followed by an if statement
>>> [x * xfor x in range (1, 6) if x% 2 = = 0]
[4, 16]
Two layers of loops, creating a full array
>>> [M + nfor m in ' ABC ' for n ' XYZ ']
[' AX ', ' AY ', ' AZ ', ' BX ', ' by ', ' BZ ', ' CX ', ' CY ', ' CZ ']
column all files and directories in the current directory
>>> Import OS
>>> [D for D inos.listdir ('. ')] -- found hidden files are listed as well.
['. TCSHRC ', '. DMRC ', ' Desktop ', '. gconf ', '. Redhat ', '. Gnome2_private ', '. BASHRC ', ' python-3.5.0b4 ', '. Python_history ' , ' Redis ', '. CSHRC ', '. Gtkrc-1.2-gnome2 ', ' python ', '. Chewing ', '. Trash ', '. Gnome ', '. Nautilus ', '. KDE ', '. Scim ', '. Lesshst ', '. Bash_logout ', ' python-3.5.0b4.tgz ', '. Gconfd ', '. Xsession-errors ', '. Bash_profile ', '. Xauthority ', '. Gnome2 ', '. Iceauthority ', '. Metacity ', '. gstreamer-0.10 ', '. Bash_history ', '. Eggcups ', '. Mysql_history ', ' shell '
Dict The list-generated
>>> d = {' X ': ' A ', ' y ': ' B ', ' z ': ' C '}
>>> [k + ' = ' + V for K, V in D.items ()]- dict key,value simultaneous iterations, is not very similar
[' Y=b ', ' x=a ', ' z=c ']
>>> L = [' Hello ', ' World ', ' IBM ', ' Apple ']
>>> [s.lower ()for S in L]
[' Hello ', ' World ', ' IBM ', ' Apple ']
Practice Section
because L contains integers and None, and cannot be used only with the lower function.
>>> L = [' Hello ', ' World ', ' Apple ', None]
>>> l_r = []
>>> Len (L)
5
>>> for I in L:
... if Isinstance (I,STR):
... l_r.append (I.lower ())
.. else:
..... l_r.append (i)
...
>>> L_r
[' Hello ', ' world ', ' apple ', None]
This article is from the "90SirDB" blog, be sure to keep this source http://90sirdb.blog.51cto.com/8713279/1796120
Python List-Generated