>>> for i, value in enumerate(['A', 'B', 'C']):
... print(i, value)
...
0 A
1 B
2 C
for i, value in enumerate(['A', 'B', 'C']):
print(i)
print(value)
0
A
1
B
2
C
def my_abs(x):
if not isinstance(x, (int, float)):
raise TypeError('bad operand type')
if x >= 0:
return x
else:
return -x
>>> my_abs('A')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in my_abs
TypeError: bad operand type
zip zip()是Python的一个内建函数,它接受一系列可迭代的对象作为参数,将对象中对应的元素打包成一个个tuple(元组),然后返回由这些tuples组成的list(列表)。若传入参数的长度不等,则返回list的长度和参数中长度最短的对象相同。利用*号操作符,可以将list unzip(解压)
>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> c = [1, 2, 3, 4, 5, 6]
>>> ziped = zip(a, b)
[(1, 4)
(2, 5)
(3, 6)]
>>>ziped=zip(a, c)
[(1, 1)
(2, 2)
(3, 3)]
>>>ziped=zip(a, b, c)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
>>> a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> zip(*a)
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
>>> map(list,zip(*a))
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
Python内置的enumerate函数这个函数可以把循环list变成 索引-元素,这样就可以在for循环中同时迭代索引和元素本身。>>> for i, value in enumerate(['A', 'B', 'C']):... print(i, value)...0 A1 B2 Cfor i, value in enumerate(['A',...