>>> l = ['A','B','C']
>>> l[0]
'A'
>>> l[0:2]
['A', 'B']
>>> l[1:2]
['B']
>>> L = list(range(100))
>>> L
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]
>>> L[:10]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> L[-10:]
[90, 91, 92, 93, 94, 95, 96, 97, 98, 99]
>>> L[:10:2]
[0, 2, 4, 6, 8]
>>> (0, 1, 2, 3, 4, 5)[:3]
(0, 1, 2)
>>> for key in [1,2,3]:
... print(key)
...
1
2
3
>>> for ch in 'ABC':
... print(ch)
...
A
B
C
>>> for key in {'a':1,'b':2,'c':3}:
... print(key)
...
a
b
c
>>> for k , v in {'a':1,'b':2,'c':3}.items():
... print('%s %s'%(k,v))
...
a 1
b 2
c 3
>>> for i,v in enumerate(['a','b']):
... print(i,v)
...
0 a
1 b
>>> from collections import Iterable
>>> isinstance([],Iterable)
True
>>> from collections import Iterator
>>> isinstance([], Iterator)
False
>>> isinstance(iter([]), Iterator)
True
>>> isinstance(iter('abc'), Iterator)
True
for x in [1, 2, 3, 4, 5]:
pass
实际上完全等价于:
# 首先获得Iterator对象:
it = iter([1, 2, 3, 4, 5])
# 循环:
while True:
try:
# 获得下一个值:
x = next(it)
* [ ] except StopIteration:
# 遇到StopIteration就退出循环
break
>>> abs(-10)
10
>>> f = abs
>>> abs
<built-in function abs>
>>> f
<built-in function abs>
>>> f(-10)
10
>>> abs = 10
>>> abs(-10)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable
>>> def add(x,y,f):
... return f(x) + f(y)
...
>>> add(-10,6,abs)
16