python 类似函数比较

1,append与extend

append是向列表中添加单个元素,一般用在向列表末尾添加一个数字或者字符串;而extend则是扩展列表,一般是向列表的末尾去合并另外一个列表。
请看下面的例子:

# case 1
a = [1, 2, 3]
b = ['b', 'c']
a.append(b)
print a, type(a[0]), type(a[3])
# output 1
#[1, 2, 3, ['b', 'c']] <type 'int'> <type 'list'>

# case 2
a = [1, 2, 3]
c = ['a', 'b']
a.extend(c)
print a, type(a[0]), type(a[3])
# output 2
# [1, 2, 3, 'a', 'b'] <type 'int'> <type 'str'>

2,map与reduce

2.1 map函数接受两个参数,第一个为函数,第二个为list,map的作用是对list中的每个元素使用该函数,最后结果以list形式返回。

squ = lambda x: x**2
# 在python3中,map()的结果为一个迭代器,可以用列表解析将结果转化为list
[ele for ele in map(squ, [1, 2, 3, 4])]
# output
#[1, 4, 9, 16]

貌似直接用列表解析也可以干上面的事情:

[ele**2 for ele in [1, 2, 3, 4]]
#output
#[1, 4, 9, 16]

2.2 reduce接受的参数跟map一样,不同的是reduce用上次运行的结果作为输入迭代进入下一次的运行,这就决定了reduce的第一个参数(函数)必须接受两个参数。
(在Python 3里,reduce()函数已经被从全局名字空间里移除了,它现在被放置在functools模块里。)

from functools import reduce
squ = lambda x, y: x*y
# 在python3中,reduce并不是迭代器
reduce(squ, [1, 2, 3, 4])
# output
#24

猜你喜欢

转载自blog.csdn.net/linkequa/article/details/88392312