Python小零碎
🍧1.pythoon中的map()函数
作为输入提供的迭代器的所有元素应用函数,迭代器可以是列表,元组,集合,字典,字符串,并且它返回可迭代的映射对象
map(function,iterator)
function:要提供给map()的必须参数,它将应用于迭代器中所有可用的项目
iterator:一个可迭代的必须对象。它可以是列表,元组等,还可以将多个迭代器对象传递给mao()函数
def square(n):
return n*n
my_list = [2,3,4,5,6,7,8,9]
updated_list = map(square, my_list)
print(updated_list)
print(list(updated_list))
#res = list(map(square,[2,3,4,5]))
#输出:
#[4, 9, 16, 25, 36, 49, 64, 81]
list_of_strings = ["5", "6", "7", "8", "9", "10"]
# map 转换
result = map(int, list_of_strings)
print(list(result)) # 注意使用list 进行了转换
#[5, 6, 7, 8, 9, 10]