Meet python: little notes 4 - high-level characteristics
Source: http://www.liaoxuefeng.com/
♥ Slice
Obtaining elements within required range from list or tuple (The results remain the same type as the original one.).
>>> L = list(range(100))
>>> L
[0, 1, 2, ..., 99]
>>> L[:3] # Access first three indexed elements, i.e. [0 1 2], 0 could be ...
[0, 1, 2] # omitted being the first index
>>> L[-10:]
[90, 91, 92, 93, 94, 95, 96, 97, 98, 99]
>>> L[:10:2] # The third number denote the slice interval
[0, 2, 4, 6, 8]
>>> (0, 1, 2, 3, 4, 5)[:3] # An example for tuple
(0, 1, 2)
>>> 'ABCDEF'[1:2] # An example for string
'B'
♥ Interation
- Using for...in to tranverse a list, tuple or other kinds of iterable structure.
# dictionary: note that keys in a dict are not scored in the list order
>>> d = {'a': 1, 'b': 2, 'c': 3}
>>> for key in d
print(key)
a
b
c
# string
>>> for ch in 'ABC'
print(ch)
A
B
C
# Decide if an object is an iterable object
>>> from collections import Iterable
>>> isinstance(123, Iterable)
False # Integer is not iterable
- Realise ordered iteration: enumerate
>>> for i, value in enumerate(['A', 'B', 'C']) # change a list to key-value
# pair
print(i, value)
0 A
1 B
2 C
♥ List comprehensions
Construct a list.
# Normal way
>>> L = []
>>> for x in range(1, 11)
l.append(x * x)
>>> L
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
# List comprehension
>>> [x * x for x in range(1, 11)]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
# Double deck
>>> [m + n for m in 'ABC' for n in 'XYZ']
['AX', 'AY', 'AZ', 'BX', 'BY', 'BZ', 'CX', 'CY', 'CZ']
# Construct a list using two variables with list comprehension
>>> d = {'x': 'A', 'y': 'B', 'z': 'C'}
>>> [k + '=' + v for k, v in d.items()]
['y=B', 'x=A', 'z=C']
♥ Generator
- A special iterable function.
- One characteristic of generator is that it breaks every time when coming across yield, restarts at exactly where it breaks last time next calling, and will not return a value unless meeting stopIteration (return value is included there). Examples of constructing a generator and calling:
# First way to produce a generator
>>> L = [x * x for x in range(10)]
>>> L
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# Change [] to (), a generator is obtained instead of a list
>>> g = (x * x for x in range(10))
>>> g
<generator object <genexpr> at 0x1022ef630>
# Second way: yield.
def fib(max): # Fibonacci sequence
n, a, b = 0, 0, 1
while n < max:
yield b
a, b = b, a + b
n = n + 1
return 'done'
>>> g = fib(6)
>>> while True:
... try:
... x = next(g) # obtain next elements in generator
... print('g:', x)
... except StopIteration as e:
... print('Generator return value:', e.value)
... break
♥ Iterator
- Object can be called using next() and return next value, actually a data flow.
- Note, iterator is different from iterable.
>>> from collections import Iterable
>>> isinstance([], Iterable)
True
>>> isinstance([], Iterable)
False
# Invert an iterable to iterator.
>>> isinstance(iter([]), Iterator)
True
- Advantage: iterator is an ordered sequence, but will not calculate next value unless required, thus is of efficiency.
- Summary
objects can be used in for are iterables;
all generators are iterators;
iterebles can be converted to iterators via iter().