>>> a=[1,2]
>>> b=[3,4]
>>> c=[5,6]
>>> zip(a,b,c)
[(1, 3, 5), (2, 4, 6)]
>>> a=[1,2,4,5]
>>> filter(lambda x:x>2,a)
[4, 5]
In[4]: a=['aa','','g']
In[6]: map(lambda x:x if x else 0,a)
Out[6]: ['aa', 0, 'g']
filter与map的区别在于 filter的结果是原列表的元素形成的列表 map要的是函数的处理结果 形成的列表
In[7]: [i if i else 0 for i in a ]
Out[7]: ['aa', 0, 'g']
In[8]: a=[1,2,3,8,6,5,1]
In[16]: sorted(set(a),key=lambda x:a.index(x)) #set后顺序不变
Out[16]: [1, 2, 3, 8, 6, 5]
>>> import collections
>>> a=[1,6,2]
>>> b=[1,4,6]
>>> dict(zip(a,b))
{1: 1, 2: 6, 6: 4}
>>> collections.OrderedDict(zip(a,b))
OrderedDict([(1, 1), (6, 4), (2, 6)]) #字典顺序不变
>>> json.dumps(dict(zip(a,b)))
'{"1": 1, "6": 4, "2": 6}'
>>> json.dumps(dict(zip(a,b)),separators=(",",":")) #separators 压缩, 和:后面的空格
'{"1":1,"6":4,"2":6}'
In[22]: for i in enumerate(b): #找回索引
... print i
...
(0, 4)
(1, 5)
(2, 6)
a='201512'
In[5]: b=['01','02','03','04','05','06','07','08','09','10']
In[12]: c=[1,2,None,4,5,None,7,8,None,10]
In[17]: d={}
In[18]: map(lambda x,y:d.update({a+x:y if y else 0}),b,c)
Out[18]: [None, None, None, None, None, None, None, None, None, None]
In[19]: d
Out[19]:
{'20151201': 1,
'20151202': 2,
'20151203': 0,
'20151204': 4,
'20151205': 5,
'20151206': 0,
'20151207': 7,
'20151208': 8,
'20151209': 0,
'20151210': 10}
>>> dict([(2,1),(1,2)])
{1: 2, 2: 1}
>>> b=collections.OrderedDict([(2,1),(1,2)])
>>> b.keys()
[2, 1]
>>> a = ['aa', 'ab', 'abc', 'bcd', 'abcde']
>>> from itertools import *
>>> for i,k in groupby(a, len): #i是长度 k是组内成员
... print i
... for j in k:
... print j
...
2
aa
ab
3
abc
bcd
5
abcde
from collections import namedtuple
students=namedtuple("student",['name','sex'])
>>> a=[students(name=1,sex=1),students(name=2,sex=2)]
>>> for i in a:
... print i.name
1
2
>>> a={"gyf":'',"hh":2}
>>> b=a.get("gyf","") or a.get("hh",'')
>>> b
2
>>> a= 4 and 1 or 2
>>> a
1
>>> a= 0 and 1 or 2
>>> a
2 第一个数为真 返回and后的 假 返回 or后面的
转载于:https://my.oschina.net/u/1458120/blog/552600