1. map(function, iterable, ...)
功能:对可迭代对象中的每个元素应用指定函数,返回一个迭代器。
参数:
-
function
:要执行的函数(可以是lambda
表达式)。 -
iterable
:一个或多个可迭代对象(如列表、元组)。
返回值:迭代器(Python 3中需用list()
等转换为列表)。
nums = [1, 2, 3]
squared = map(lambda x: x**2, nums) # 平方操作
print(list(squared)) # 输出 [1, 4, 9]
# 多参数示例
sums = map(lambda x, y: x + y, [1, 2], [3, 4])
print(list(sums)) # 输出 [4, 6]
注意:
-
Python 3返回迭代器,节省内存但需显式转换。
-
多可迭代对象时,函数需接收对应数量参数,且按最短长度截断。
2. list([iterable])
功能:将可迭代对象转换为列表。
参数:
-
iterable
(可选):字符串、元组、字典(返回键列表)等。
返回值:列表对象。
str_list = list("hello") # ['h', 'e', 'l', 'l', 'o']
tuple_list = list((1, 2, 3)) # [1, 2, 3]
empty_list = list() # []
#从字符串创建列表
string = "hello"
string_list = list(string)
print(string_list) # 输出: ['h', 'e', 'l', 'l', 'o']
#从元组创建列表
tuple = (1, 2, 3)
tuple_list = list(tuple)
print(tuple_list) # 输出: [1, 2, 3]
#从字典创建列表
dictionary = {'a': 1, 'b': 2, 'c': 3}
keys_list = list(dictionary)
print(keys_list) # 输出: ['a', 'b', 'c']
注意:
-
非可迭代对象(如整数)会报
TypeError
。 -
空参数返回空列表,等效于
[]
。
3. len(s)
功能:返回对象的长度(元素个数)。
参数:
-
s
:字符串、列表、元组、字典、集合等。
返回值:整数。
print(len("hello")) # 5
print(len([1, 2, 3])) # 3
print(len({"a": 1, "b": 2})) # 2
注意:
-
自定义类需实现
__len__()
方法才支持len()
。 -
字典返回键的数量,集合返回元素数量。
4. iter(object[, sentinel])
功能:生成可迭代对象的迭代器。
参数:
-
object
:支持迭代协议(有__iter__()
)或序列协议(有__getitem__()
)。 -
sentinel
(可选):若提供,object
需为可调用对象,迭代直到返回sentinel
。
返回值:迭代器对象。
nums = [1, 2, 3]
it = iter(nums)
print(next(it)) # 1
print(next(it)) # 2
# 文件逐行读取(直到空行)
with open('file.txt') as f:
for line in iter(f.readline, ''):
print(line)
5. hex(x)
功能:将整数转换为小写十六进制字符串(前缀0x
)。
参数:
-
x
:整数。
返回值:字符串,如'0x1a'
。
print(hex(255)) # 0xff
print(hex(-42)) # -0x2a
注意:
-
非整数参数会报
TypeError
。 -
转换结果可通过
format(x, '#X')
转为大写。
6. hash(object)
功能:返回对象的哈希值(整数)。用于字典键、集合成员快速查找。
参数:
-
object
:不可变类型(如字符串、元组、数字)。
返回值:整数哈希值。
print(hash("hello")) # 随机整数(Python 3.3+因安全随机化)
print(hash(123)) # 123
注意:
-
可变对象(如列表、字典)不可哈希,会报
TypeError
。 -
哈希值在程序生命周期内一致,但不同解释器或版本可能不同。
总结
-
map()
:批量处理数据,惰性求值。 -
list()
:灵活构造列表,处理迭代结果。 -
len()
:通用长度查询,需对象实现__len__
。 -
iter()
:手动控制迭代过程,支持高级迭代逻辑。 -
hex()
:整数转十六进制,调试或编码常用。 -
hash()
:确保对象可哈希,优化数据结构性能。