题目描述
列表[1,2,3,4,5]
,请使用map()函数
输出[1,4,9,16,25]
,并使用列表推导式提取出大于10的数,最终输出[16,25]
规则
- 使用map函数
- 使用列表推导式
期望输出
[16,25]
解题
def func2():
list1 = [1, 2, 3, 4, 5]
return [ i for i in map(lambda x: x**2, list1) if i > 10]
相关知识
map函数
语法:map(function, iterable1, ...iterable2...)
第一个参数 function
接收一个函数类型,第二个参数iterable
接收多个序列类型。具体功能为:
以参数序列中的每一个元素调用 function 函数,返回包含每次 function 函数返回值的新的映射,即<map object at 0x0000017ADB930B50>
类型,这个映射对象可以转为list
,tuple
,set
。
当iterable
为一个参数
为字符串
>>> a = 'hello'
>>> str(map(lambda x:x.upper(), a))
'<map object at 0x0000017ADB930B50>'
>>>
>>> list(map(lambda x:x.upper(), a))
['H', 'E', 'L', 'L', 'O']
>>>
>>>
>>> set(map(lambda x:x.upper(), a))
{'L', 'E', 'H', 'O'}
>>>
>>>
>>> dict(map(lambda x:x.upper(), a))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: dictionary update sequence element #0 has length 1; 2 is required
为列表
>>> foo = [1, 2, 3, 4]
>>> list(map(lambda x: x+1, foo))
[2, 3, 4, 5]
>>>
>>>
>>> tuple(map(lambda x: x+1, foo))
(2, 3, 4, 5)
>>>
>>>
>>> set(map(lambda x: x+1, foo))
{2, 3, 4, 5}
为元组
>>> bar = (1,2,3,4,5)
>>>
>>> tuple(map(lambda x: x*10, bar))
(10, 20, 30, 40, 50)
>>>
>>>
>>> list(map(lambda x: x*10, bar))
[10, 20, 30, 40, 50]
>>>
>>>
>>> set(map(lambda x: x*10, bar))
{40, 10, 50, 20, 30}
为集合
>>> foo2 = {1,2,3}
>>>
>>>
>>> set(map(lambda x: x*10, foo2))
{10, 20, 30}
当iterable
为多个参数
依次比较两个列表中元素的大小
>>> map_object = map(lambda x,y : x>y, [1, 2, 3], [0, 3, 1, 2, 6])
>>> map_object
<map object at 0x0000017ADB822130>
>>>
>>>
>>> list(map_object)
[True, False, True]
三个列表中元素相加
>>> list(map(lambda x,y,z: x+y+z, [1,2,3],[1,2,3],[8,6,4]))
[10, 10, 10]