全部版块 我的主页
论坛 数据科学与人工智能 数据分析与数据科学 python论坛
1241 1
2015-07-01
In loops, we call methods, but sometimes this leads to code that is unclear.
It is hard to maintain, and bugs emerge. with map, we declareatively apply methods to collections.

Map requires fewer statements and variables. It is a form of declarative programming. We tell
the program the result we want, not how to compute it.

Example:

items=[1,2,3]

for r in map(lambda x: x+1, items):
   print r

Output:
2
3
4

Map returns an iterator. we often must convert this back into the desired collection type.
here, we use map on a list. we then convert the result of map back into a list.

Example:

items=[7,8,9]
items2=list( map(lambda x: x*2, items)):
print items
print items2

Output:
[7,8,9]
[14, 16, 18]


二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

全部回复
2015-7-1 03:12:26

Example 3:

names=["San Jose", "San Francisco", "Santa Fe", "Houston"]

count = sum(map(lambda s: s.startswith("San"), names))

print count

Output:
3

Example 4:

More than one iterable can be used as arguments to map.

a =[1,2 ,3]
b=[2,3,4,5]

result = list(map(lambda x, y: x* y, a, b)

print(result)

Output:
[2, 6, 12]
二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

相关推荐
栏目导航
热门文章
推荐文章

说点什么

分享

扫码加好友,拉您进群
各岗位、行业、专业交流群