# Python — Map, Filter, Reduce

2023-03-07 11:55:35  阅读：340  来源： 互联网

```l1 = [“3”，“5”，“9”，“12”，“25”]x = l1[0]
+1

```----------------------------------------------------------------------
-----

）

+1
3 print（x）

```对于范围（len（L1））：
l1[i] = int（L1[i]）```

```x = L1[0]+1

`4`

```l2 = [“3”，“5”，“9”，“12”，“25”]l2 = list（map（int，l2））y = l2[0]
+1
print（y）
```
`4`

Now let’s have a look at a few other examples as well, suppose we want to find out the square values of an entire list, let’s see how we can do that with the help of the map function.

First, let’s write a function ‘sq’ which will return the squared value of a given number

```def sq(a):
return a*a```

Now let’s create a list named l3 with integer elements

```l3 = [3,5,7,2,9]
l4 = list(map(sq,l3))
print(l4)```
`[9, 25, 49, 4, 81]`

As we can see, we are able to get the squared value for all the elements present in the list.

Now let’s look into something more complicated, what we are trying to achieve now is to get the square and cube of numbers from 0,8, stored in a list. We will use the map function, lambda function, and also our def keyword to describe the square and cube functions now. Then we will use a for loop to create the list.

```def sq(a):
return a*a
def cube(a):
return a*a*a
func = [sq,cube]
for i in range(8):
rslt = list(map(lambda x:x(i) ,func))
print(rslt)```
```[0, 0]
[1, 1]
[4, 8]
[9, 27]
[16, 64]
[25, 125]
[36, 216]
[49, 343]```

Filter

As the name suggests, the filter function helps us in filtering a given set of iterables , as an argument it takes the stated function based on which we will be filtering our iterables and then it takes the iterables themselves as the arguments. Below 3 types of filters are given, one will filter numbers greater than 10 from the list, one will filter numbers lesser than 10, and one will have multiple conditioning that states the number should be greater than 10 but lesser than 15.

```l1 = [34,12,5,8,11,14,19,10,1,50]
def grt_condi(num):
return num>10
def lsr_condi(num):
return num<10
def multi_condi(num):
return num>10 and num<15

l2 = list(filter(grt_condi,l1))
l3 = list(filter(lsr_condi,l1))
l4 = list(filter(multi_condi,l1))

print(l2)
print(l3)
print(l4)```
```[34, 12, 11, 14, 19, 50]
[5, 8, 1]
[12, 11, 14]```

Reduce

Let’s understand what reduce function does and what problem it solves, to understand this, let’s first take a problem statement and our traditional walkaround in solving that.

Let’s say there is a list and we want to get the summation of all the integers present in the list

```l6 = [2,3,6,5,8,9,10]
x = 0
for i in l6:
x = x+i
print(x)```
`43`

```从 functools 导入 reduce
l7 = reduce（lambda x，y：x+y ， l6）print（l7）
```
`43`

2. 关于本站的所有留言、评论、转载及引用，纯属内容发起人的个人观点，与本站观点和立场无关；
3. 关于本站的所有言论和文字，纯属内容发起人的个人观点，与本站观点和立场无关；
4. 本站文章均是网友提供，不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属；如您发现该文章侵犯了您的权益，可联系我们第一时间进行删除；
5. 本站为非盈利性的个人网站，所有内容不会用来进行牟利，也不会利用任何形式的广告来间接获益，纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。