python learning Notes - List of Formula

I.e. formula list fancy application cycle, generating a list by the circulation of a regular pattern.

1.

>>> list(range(1, 11))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

2.

>>> [x * x for x in range(1, 11)] [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

3.

You can also add back loop for determining if, so that we can filter out only the even square of:

>>> [x * x for x in range(1, 11) if x % 2 == 0] [4, 16, 36, 64, 100]

4.

May also be used two cycles, the whole arrangement can be generated:

>>> [m + n for m in 'ABC' for n in 'XYZ'] ['AX', 'AY', 'AZ', 'BX', 'BY', 'BZ', 'CX', 'CY', 'CZ']

5. Exercise: if the list contains both the string, and contains an integer, since no non-string type lower()method, it will be given a list of formula: using the built-in isinstancefunction can not determine whether a variable is a string:

L1 = ['Hello', 'World', 18, 'Apple', None]

L2 = [s.lower() for s in L1 if isinstance(s,str)]

 

 

 

 

Guess you like

Origin www.cnblogs.com/cyjwdx102355/p/11127936.html