Python _ advanced features
Python advanced features
Author: lxy
Slicing, iteration, list generation, generator
Slice
The less code Python, the simpler the better,
We want to take a part of the element in a list. We can use the judgment + loop implementation. In Python, we provide a special method-slicing.
Slice used to obtain an element in the list
Tuple, str, and so on are both regarded as a list of fragments obtained by using slices or their original corresponding types.
Example 1. Slice the list
- >>> N = [1, 3, 2, 5, 6, 8]
- >>> N [0: 3] # tail excluded
- [1, 3, 2]
- >>> N [-2:] # You can use reverse truncation.
- [6, 8]
- >>> Copy the code
Example 2. Slice tuple
- >>> T = ('A', 's', 'D', 'D ')
- >>> T [: 3] # truncated from 0 by default
- ('A', 's', 'D') # tuple
- >>> Copy the code
Example 3. segment str
- >>> S = 'dfsafsf'
- >>> S [: 3]
- 'Dfs '# string slices or strings
- >>># No function exists for string Truncation in Python. You only need to use slice to copy the code.
Iteration
It is called iteration.
In c or Java, iterative list is done by subscript.
Objects such as list can complete iteration with a lower mark, while dict, str, and so on can complete iteration without a lower mark through Python's for... in.
Itervalues () can be used to iterate the v
You can use iteritems () to iterate the k_V of dict.
How to determine whether an object can be iterated
Determined by the iterable type of the collections Module
Example:
- >>> From collections import Iterable # obtain the Iterable type of the collections Module
- >>> Isinstance ('dfdas', Iterable) # determine whether iteration is allowed
- True
- >>> Isinstance (555, Iterable)
- False
- >>> Copy the code
Implement subscript loop in Python. The Python built-in enumerate function can convert a list into an index-element.
Example:
- >>> For I, v in enumerate ('s ', 'D', 'G ')):
- Print (I, v)
- 0 s
- 1 d
- 2g
- >>> Copy the code
List Generator
Range ()#
1. Generate a continuous integer sequence through range ()
2. pass -- <表达式> -- Generate a list
Example 1: generate an integer Sequence
- >>> A = range (3)
- >>> For I in:
- Print (I)
- 0
- 1
- 2
- >>> Copy the code
Example 2: generate a special number
- >>> C = [x * x for x in range (2, 5)]
- >>> C
- [4, 9, 16]
- >>> Copy the code
Adding if and nested in list generation
Filter Using if
Example,
- >>> A = [x * x for x in range (5) if x> 2] # Add if to filter x.
- >>>
- [9, 16]
- >>> Copy the code
Example,
- >>> [M + n for m in 'abc' for n in 'xyz']
- ['Ax ', 'ay', 'az', 'bx ', 'by', 'bz', 'cx', 'cy ', 'cz']
- >>> Copy the code
For example, use the list generator to list all folders and directory names in the current directory.
- >>> Import OS # import OS Module
- >>> [D for d in OS. listdir ('.')] # The specified path is in brackets.
- ['Dls', 'Doc', 'include ', 'lib', 'libs', 'scripts', 'tcl', 'tools']
- >>> Copy the code
Generator
However, due to memory restrictions, the list capacity must be limited. In addition, creating a list containing 1 million elements not only occupies a large storage space, but if we only need to access the first few elements, the space occupied by the vast majority of elements is wasted.
Python provides this solution. The list elements are computed through an algorithm, and the subsequent elements are constantly computed during the loop process without the need to create a complete list.
Python stores algorithms and calls next () each time ()
Create generator
1. Change [] of the List generation type ()
2. After the yield keyword is added to a common function, this function is not a common function, but a generator function, which is executed every time next () is called, when the yield statement is returned, the yield statement is returned from the previous execution.
Example 1,
- >>> B = (x for x in range (10 ))
- >>> B
- At 0x02CB1418>
- >>> Next (B) # obtain the next element. Because generator is also iteratable, The for loop is generally used for iteration.
- 0
- >>> Copy the code
Example 2,
- >>> Def f ():
- Print ('s1 ')
- Yield 1
- Print ('s2 ')
- Yield 2
- >>> A = f ()
- >>> Next ()
- S1
- 1
- >>> Next ()
- S2
- 2
- >>> Next ()
- Traceback (most recent call last ):
- File" ", Line 1, in
- Next ()
- StopIteration # An error is thrown when yield is not available for execution.
- >>> Copy the code
The generator command after function transformation ends when return or function body is completed,
Example:
- >>> Def f ():
- Print ('s1 ')
- Yield 1
- Return
- Print ('s2 ')
- Yield 2
- >>> For I in f ():
- Print (I)
-
- S1
- 1
- >>>>>> Def f ():
- Print ('s1 ')
- Yield 1
- Return
- Print ('s2 ')
- Yield 2
- >>> For I in f ():
- Print (I)
- S1
- 1
- >>> Copy the code
From group: Java User Group