欢迎访问宙启技术站
智能推送

Python中使用map()函数的十个示例

发布时间:2023-07-06 02:56:46

map()函数是Python中非常常用的内置函数,它可以将一个函数应用于一个可迭代对象的每个元素,并返回一个包含结果的可迭代对象。map()函数的基本语法如下:

map(function, iterable)

其中,function是函数对象,iterable是可迭代的对象,比如列表、元组、字符串等。下面是十个示例,展示了map()函数在不同场景下的应用。

个示例:将列表中的每个元素都加1

numbers = [1, 2, 3, 4, 5]
result = list(map(lambda x: x + 1, numbers))
print(result)
输出结果为:[2, 3, 4, 5, 6]

第二个示例:将字符串中的每个字符转换成大写

string = "hello"
result = ''.join(map(lambda x: x.upper(), string))
print(result)
输出结果为:HELLO

第三个示例:将两个列表中对应位置的元素相加

list1 = [1, 2, 3]
list2 = [4, 5, 6]
result = list(map(lambda x, y: x + y, list1, list2))
print(result)
输出结果为:[5, 7, 9]

第四个示例:将元组中的每个元素转换成字符串

tuple1 = (1, 2, 3, 4)
result = tuple(map(lambda x: str(x), tuple1))
print(result)
输出结果为:('1', '2', '3', '4')

第五个示例:将字符串中的每个单词首字母转换成大写

string = "hello world"
result = ' '.join(map(lambda x: x.capitalize(), string.split()))
print(result)
输出结果为:Hello World

第六个示例:将二维列表中的每个元素乘以2

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
result = [list(map(lambda x: x*2, row)) for row in matrix]
print(result)
输出结果为:[[2, 4, 6], [8, 10, 12], [14, 16, 18]]

第七个示例:将字典中的每个键值对拼接成字符串

dictionary = {'name': 'Alice', 'age': 20, 'gender': 'female'}
result = ', '.join(map(lambda x: str(x[0]) + ': ' + str(x[1]), dictionary.items()))
print(result)
输出结果为:name: Alice, age: 20, gender: female

第八个示例:将字符串中的每个字符转换成ASCII码

string = "hello"
result = list(map(lambda x: ord(x), string))
print(result)
输出结果为:[104, 101, 108, 108, 111]

第九个示例:将列表中的每个整数转换成二进制字符串

numbers = [1, 2, 3, 4, 5]
result = list(map(lambda x: bin(x)[2:], numbers))
print(result)
输出结果为:['1', '10', '11', '100', '101']

第十个示例:将字典中的每个值取相反数

dictionary = {'a': 1, 'b': 2, 'c': 3}
result = {key: -value for key, value in dictionary.items()}
print(result)
输出结果为:{'a': -1, 'b': -2, 'c': -3}

以上是map()函数在不同场景下的使用示例。可以看出,map()函数可以方便地对可迭代对象中的每个元素进行处理,并返回处理结果。同时,也可以配合lambda表达式使用,进一步简化代码。在日常的编程中,map()函数是一个非常实用的工具,可以帮助我们快速完成各种批量操作。