python

Python包含以下函数:

1 cmp(list1, list2) 比较两个列表的元素

2 len(list) 列表元素个数

3 max(list) 返回列表元素最大值

4 min(list) 返回列表元素最小值

5 list(seq) 将元组转换为列表

list方法

1 list.append(obj) 在列表末尾添加新的对象

2 list.count(obj) 统计某个元素在列表中出现的次数

3 list.extend(seq) 在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表)

4 list.index(obj) 从列表中找出某个值第一个匹配项的索引位置

5 list.insert(index, obj) 将对象插入列表

6 list.pop(obj=list[-1]) 移除列表中的一个元素(默认最后一个元素),并且返回该元素的值

7 list.remove(obj) 移除列表中某个值的第一个匹配项

8 list.reverse() 反向列表中元素

9 list.sort([func]) 对原列表进行排序

python的高级特性切片&截取

list1  = [1,2,3,4,5,6,7]
list2 = list1[:3]#0~3,但是不包含3,和C++STL中的迭代器有点像
list2
结果 [1, 2, 3]

list2[0]
结果 1

list2[2] = 0
list2
结果 [1, 2, 0]

list1
结果 [1, 2, 3, 4, 5, 6, 7]

list1[2] =10
list2
结果 [1, 2, 0]

加-(负号)表示取倒数第几个

list1
结果 [1, 2, 10, 4, 5, 6, 7]

list1[-5:-1]
结果 [10, 4, 5, 6]

list1[-1]
结果 7

每隔整数个元素取一个

 list1[::2]

 结果 [1, 10, 5, 7]

迭代(直接在对象上)

for ch in 'ABC':
    print ch
结果 A
B
C

for i,j in [(1,2),(3,4),(5,6)]:
print i,j
结果 1 2
3 4
5 6

列表生成器

#生成一个列表
#方式一
import numpy as np
l = []
for i in xrange(1,11):
    l.append(i)

#方式二,列表生成器 [x for x in range(1,11)]

结果 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

加判断语句

  [x for x in xrange(1,11) if x % 2 == 0]

  结果 [2, 4, 6, 8, 10]

  [x for x in np.random.random(10) if x < 0]

  结果 []

多层循环

  [m + n for m in 'abc' for n in 'xyz']

  结果 ['ax', 'ay', 'az', 'bx', 'by', 'bz', 'cx', 'cy', 'cz']

 

*生成器(大数据量下的优化方式)生成器generator两种方式,一般情况下需要配合for使用

1)生成器表达式:通过列表表达式,不同之处是将[ ]换成()

gen = (x **2 for x in range(5))
gen
<generator object <genexpr> at 0x0000000004358798>
for n in gen: print n

结果
0
1
4
9
16

2)生成器函数(yield 标识每次迭代的输出)

def myfun():
    n = 1
    while n < 10:
        yield n
        n = n + 2

genFun = myfun()
for n in genFun:
    print n

结果
1
3
5
7
9

python函数式编程高阶函数(函数名即为变量名,可以将函数名作为函数参数)

abs(-5)
结果 5

f= abs
f
<function abs>
f(-4)
结果 4

l = [1,2,3,-4,-5,-1,-2]
sorted(l,key = f)#按绝对值进行排序
结果 [1, -1, 2, -2, 3, -4, -5]

def add1(x, y,key = f):
return f(x) + f(y)
add1(1,-2,f)
结果 3

map/reduce

l = [1,2,3,-4,-5]
map(abs,l)
结果 [1, 2, 3, 4, 5]

import functools
addAbs = functools.partial(add1,key = abs)#用偏函数固定参数
reduce(addAbs,l)
结果 ·15

filter过滤

  filter(lambda x:x>0,l)

  结果 [1, 2, 3]

filter(function,obj),function返回Ture或者Flase,obj为一个序列

sorted排序 sorted是高阶函数,可以接受函数参数

 sorted(l,key = abs)

 结果 [1, 2, 3, -4, -5]

 from collections import Iterator

 L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)]

 L = dict(L)

 L

 #判断是不是迭代器

 isinstance(iter( L.keys()),Iterator)

 #生成迭代器iter()函数

 sorted(iter(L.keys()),key = str.lower)

 结果 ['Adam', 'Bart', 'Bob', 'Lisa']


原文地址:https://www.cnblogs.com/xzjf/p/9271709.html