python 基础——常用功能片段
1. 元素去重
data = [1,2,3,4,4,5,5,6]
res = set(data)
2. 元素去重排序
res = sorted(set(data))
2. 打印重复的元素
res = [x for x in data if data.count(x) > 1]
3. 阶乘
num = 10 res = reduce(lambda x, y: x*y, range(num+1)[1:])
6. 列表推导式
origin = ['a', 'b', 'c', 'z'] print [x for x in origin if x is not 'z'] # ['a', 'b', 'c'] print [x for x in list(enumerate(origin, 5)) if x is not 'z'] # [(5, 'a'), (6, 'b'), (7, 'c'), (8, 'z')]
7. 字典推导式
origin = ['a', 'b', 'c', 'z'] res = {x: origin.index(x) for x in origin} # {'a': 0, 'c': 2, 'b': 1, 'z': 3} print type(res) # <type 'dict'>
8. 集合推导式
origin = ['a', 'b', 'c', 'z'] print {x*2 for x in origin} # set(['aa', 'cc', 'zz', 'bb'])
9. 生成器推导式(有点像元组)
origin = ['a', 'b', 'c', 'z'] res = (x*2 for x in origin) print res # <generator object <genexpr> at 0x7fe2ca76d640> print type(res) # <type 'generator'>
10.生成器和其它集合的转换
def test(): for i in [1, 2,3]: yield i res = test() print res # <generator object test at 0x7f404d077640> res1 = set(res) print res1 # set([1, 2, 3]) res2 = list(res) print res2 #为空 生成器是有状态的,不能反复调用 res3 = tuple(res) print res3 #为空 生成器是有状态的,不能反复调用