getattr(object, name[, default]); #从对象object中获取名称为name的属性,等效于调用object.name
第二个参数default为可选参数,如果object中含有name的属性,则返回name属性的值,如果没有name属性,则返回default的值,如果default没有传入值,则报错。
zip #将两个序列缝合起来,并返回一个由元组组成的序列。返回值是一个适合迭代的对象,要查看其内容,可使用list将其转换成列表
例子:
names = [‘Anna’, ‘Beth’, ‘George’, ‘Damon’]
ages = [12, 45, 32, 102]
list(zip(names, ages))
[(‘Anna’, 12), (‘Beth’, 45), (‘George’, 32), (‘Damon’, 102)]
for name, age in zip(names, ages):
… print(name, ‘is’, age, ‘years old.’)
…
Anna is 12 years old.
Beth is 45 years old.
George is 32 years old.
Damon is 102 years old.
函数zip可用于缝合任意数量的序列,当序列长度不同时,zip将在最短的序列用完后停止缝合。
例子:
list(zip(range(5), range(10000)))
[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]
enumerate #迭代索引-值对,其中索引是自动提供的
例子:
for index, string in enumerate(strings):
… if ‘xxx’ in string:
… strings[index] = ‘[censored]’
…
sorted #返回已排序的序列
reversed #返回反转的序列
例子:
sorted([3, 1, 4, 1])
[1, 1, 3, 4]
sorted(‘Hello, world!’)
[’ ‘, ‘!’, ‘,’, ‘H’, ‘d’, ‘e’, ‘l’, ‘l’, ‘l’, ‘o’, ‘o’, ‘r’, ‘w’]
list(reversed(‘Hello, world!’))
[’!', ‘d’, ‘l’, ‘r’, ‘o’, ‘w’, ’ ', ‘,’, ‘o’, ‘l’, ‘l’, ‘e’, ‘H’]
map:返回一个可迭代对象,且该可迭代对象使用一次后为空,因为调用迭代器时执行了__next__,消耗了迭代对象,每次访问指向下一个元素,到结束时指向末尾。
m = map(str, range(3))
list(m)
['0', '1', '2']
list(m)
[]
本文介绍了Python中的几个内置函数:getattr用于获取对象属性,zip用于合并序列,enumerate用于生成索引值和值对,sorted和reversed用于排序和反转序列,以及map用于映射序列操作。每个函数的用法和示例都被详细解释。

被折叠的 条评论
为什么被折叠?



