map的使用:map(function, iterable, ...)
??map()函數(shù)接收兩個(gè)參數(shù),一個(gè)是函數(shù),一個(gè)是Iterable,map將傳入的函數(shù)依次作用到序列的每個(gè)元素,并把結(jié)果作為新的Iterator返回。
>>> def f(x):
... return x + x
...
>>> r = map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> list(r)
[2, 4, 6, 8, 10, 12, 14, 16, 18]
# 提供了兩個(gè)列表,對(duì)相同位置的列表數(shù)據(jù)進(jìn)行相加
>>> map(lambda x, y: x + y, [1, 3, 5, 7, 9], [2, 4, 6, 8, 10])
[3, 7, 11, 15, 19]
reduce的使用:reduce(function, iterable[, initializer])
??reduce把一個(gè)函數(shù)作用在一個(gè)序列[x1, x2, x3, ...]上,這個(gè)函數(shù)必須接收兩個(gè)參數(shù),reduce把結(jié)果繼續(xù)和序列的下一個(gè)元素做累積計(jì)算。
>>> from functools import reduce
>>> def add(x, y):
... return x + y
...
>>> reduce(add, [1, 3, 5, 7, 9])
25
>>> reduce(lambda x, y: x+y, [1,2,3,4,5]) # 使用 lambda 匿名函數(shù)
15
from functools import reduce
def add(x,y):
return x + y
print (reduce(add, range(1, 101)))
filter的使用:filter(function, iterable)
??filter()也接收一個(gè)函數(shù)和一個(gè)序列。和map()不同的是,filter()把傳入的函數(shù)依次作用于每個(gè)元素,然后根據(jù)返回值是True還是False決定保留還是丟棄該元素。
def is_odd(n):
return n % 2 == 1
list(filter(is_odd, [1, 2, 4, 5, 6, 9, 10, 15]))
# 結(jié)果: [1, 5, 9, 15]
def not_empty(s):
return s and s.strip()
list(filter(not_empty, ['A', '', 'B', None, 'C', ' ']))
# 結(jié)果: ['A', 'B', 'C']
- filter()函數(shù)返回的是一個(gè)Iterator,也就是一個(gè)惰性序列,所以要強(qiáng)迫f(wàn)ilter()完成計(jì)算結(jié)果,需要用list()函數(shù)獲得所有結(jié)果并返回list。
sorted的使用:sorted(iterable[, cmp[, key[, reverse]]])
- Python內(nèi)置的sorted()函數(shù)就可以對(duì)list進(jìn)行排序:
>>>a = [5,7,6,3,4,1,2]
>>> b = sorted(a) # 保留原列表
>>> a
[5, 7, 6, 3, 4, 1, 2]
>>> b
[1, 2, 3, 4, 5, 6, 7]
- 此外,sorted()函數(shù)也是一個(gè)高階函數(shù),它還可以接收一個(gè)key函數(shù)來(lái)實(shí)現(xiàn)自定義的排序,例如按絕對(duì)值大小排序:
>>> sorted([36, 5, -12, 9, -21], key=abs)
#key指定的函數(shù)將作用于list的每一個(gè)元素上,并根據(jù)key函數(shù)返回的結(jié)果進(jìn)行排序。對(duì)比原始的list和經(jīng)過(guò)key=abs處理過(guò)的list:
#list = [36, 5, -12, 9, -21]
#keys = [36, 5, 12, 9, 21]
[5, 9, -12, -21, 36]
#字符串排序
>>> sorted(['bob', 'about', 'Zoo', 'Credit'])
['Credit', 'Zoo', 'about', 'bob']
默認(rèn)情況下,對(duì)字符串排序,是按照ASCII的大小比較的,由于'Z' < 'a',結(jié)果,大寫(xiě)字母Z會(huì)排在小寫(xiě)字母a的前面。
- 要進(jìn)行反向排序,不必改動(dòng)key函數(shù),可以傳入第三個(gè)參數(shù)reverse=True:
>>> sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower, reverse=True)
['Zoo', 'Credit', 'bob', 'about']
raw_input的使用:raw_input([prompt])
- prompt: 可選,字符串,可作為一個(gè)提示語(yǔ)。
- raw_input() 將所有輸入作為字符串看待
>>>a = raw_input("input:")
input:123
>>> type(a)
<type 'str'> # 字符串
>>> a = raw_input("input:")
input:runoob
>>> type(a)
<type 'str'> # 字符串
>>>
- input() 需要輸入 python 表達(dá)式
>>>a = input("input:")
input:123 # 輸入整數(shù)
>>> type(a)
<type 'int'> # 整型
>>> a = input("input:")
input:"runoob" # 正確,字符串表達(dá)式
>>> type(a)
<type 'str'> # 字符串
>>> a = input("input:")
input:runoob # 報(bào)錯(cuò),不是表達(dá)式
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1, in <module>
NameError: name 'runoob' is not defined
<type 'str'>