os.mkdir和os.mkdirs的区别?
前者如果“中间路径”不存在,会抛出异常,后者则会自动创建中间路径。
map(function, iterable)
对于可迭代函数```iterable```中的每一个函数,执行```function```,并将结果作为list返回。可以说,```map(f, iterable)``` **基本等价于** ``` [f(x) for x in iterable]```
>>> def add100(x):
... return x+100
...
>>> hh = [11,22,33]
>>> map(add100,hh)
[111, 122, 133]
reduce(function, iterable, initializer=None)
从可迭代对象iterable
头部的两个元素开始,循环调用function
使结果减少到一个元素,并用这个新元素继续和后一个元素reduce
,直至最后一个元素。如果initializer
有值,则它会被放到iterable
序列的头部。
例如:
reduce(lambda x, y: x+y, [1, 2, 3, 4, 5], 10)
//计算(((((10+1)+2)+3)+4)+5)
filter(function, iterable)
对iterable中的每一个元素,执行function,如果返回值是true则将其添加到一个list中,最后返回该list. ```filter(function, iterable)```**等价于**```[item for item in iterable if function(item)]```.
使用dict
统计元素个数更简洁的写法
以前一直用这样:
mlist = [1, 2, 2, 4, 1, 3, 7, 2]
mdict = {}
for i in mlist:
if i not in mdict:
mdict[i] = 0
mdict[i] += 1
昨天发现一种更简洁的写法:
mlist = [1, 2, 2, 4, 1, 3, 7, 2]
mdict = {}
for i in mlist:
mdict.get(i, 0) + 1 # get获取key为i的value,如果没有则默认为0
给dict
排序
有时我们不想使用collections
(一种有序的dict数据结构),比如代码已经写好了懒得改,怎么办呢?
方法一:使用lambda
dic = {'a':31, 'bc':5, 'c':3, 'asd':4, 'aa':74, 'd':0}
mdict= sorted(dic.iteritems(), key=lambda d:d[1], reverse = True)
方法二:使用operator
dic = sorted(dic .items(), key = operator.itemgetter(1), reverse = True)