Python join sorted sort map reduce 函数解析

1.字符串转list (list)函数

    s = 'abcde'
    print list(s)spa

    ['a', 'b', 'c', 'd', 'e']字符串

2.list转字符串 (join)lambda

    tmp = ['a', 'b', 'c', 'd', 'e']
    print ''.join(tmp)map

    abcdeim

3.字符串转dict (eval)sort

   将字符串str当成有效的表达式来求值并返回计算结果。dict

    s =  "{'name' : 'jim', 'sex' : 'male', 'age': 18}"
    s_dict = eval(s)
    print type(s_dict)
    print s_dict['name']

   <type 'dict'>
   jimdi

4. map函数co

map()函数接收两个参数,一个是函数,一个是序列,map将传入的函数依次做用到序列的每一个元素,并把结果做为新的list返回。

使用map函数须要预先定义一个函数。以下,定义了add函数。

def add(x):
    return x+2

tmp = [1,2,3,4,5,6]
print map(add, tmp)

[3, 4, 5, 6, 7, 8]

 

5.reduce函数

reduce把一个函数做用在一个序列[x1, x2, x3...]上,这个函数必须接收两个参数,reduce把结果继续和序列的下一个元素作累积计算

    def sum(x,y):
        return x+y

    tmp = [1,2,3,4,5,6]
    print reduce(sum, tmp)

    21

6.sorted

sort()与sorted()的不一样在于,sort是在原位从新排列列表,而sorted()是产生一个新的列表。

print sorted([5, 2, 3, 1, 4])

                         [1, 2, 3, 4, 5]

 L = [('b',2),('a',1),('c',3),('d',4)]
 print sorted(L, cmp=lambda x,y:cmp(x[1],y[1]))
 print sorted(L, key=lambda x:x[1])

 [('a', 1), ('b', 2), ('c', 3), ('d', 4)]  [('a', 1), ('b', 2), ('c', 3), ('d', 4)]

相关文章
相关标签/搜索