对于第一个问题,您应该做的第一件事是使用来自运算符模块的itemgetter按第二个字段对列表进行排序:
x = [ ['4', '21', '1', '14', '2008-10-24 15:42:58'], ['3', '22', '4', '2somename', '2008-10-24 15:22:03'], ['5', '21', '3', '19', '2008-10-24 15:45:45'], ['6', '21', '1', '1somename', '2008-10-24 15:45:49'], ['7', '22', '3', '2somename', '2008-10-24 15:45:51'] ] from operator import itemgetter x.sort(key=itemgetter(1))
然后你可以使用itertools的groupby函数:
from itertools import groupby y = groupby(x, itemgetter(1))
现在y是一个包含元组(元素,项迭代器)的迭代器.解释这些元组比显示代码更令人困惑:
for elt, items in groupby(x, itemgetter(1)): print(elt, items) for i in items: print(i)
哪个印刷品:
21['4', '21', '1', '14', '2008-10-24 15:42:58'] ['5', '21', '3', '19', '2008-10-24 15:45:45'] ['6', '21', '1', '1somename', '2008-10-24 15:45:49'] 22 ['3', '22', '4', '2somename', '2008-10-24 15:22:03'] ['7', '22', '3', '2somename', '2008-10-24 15:45:51']
对于第二部分,您应该使用已在此处提到的列表推导:
from pprint import pprint as pp pp([y for y in x if y[3] == '2somename'])
哪个印刷品:
[['3', '22', '4', '2somename', '2008-10-24 15:22:03'], ['7', '22', '3', '2somename', '2008-10-24 15:45:51']]
如果你把它分配给var"a"......
python 2.x:
#1:
a.sort(lambda x,y: cmp(x[1], y[1]))
#2:
filter(lambda x: x[3]=="2somename", a)
python 3:
#1:
a.sort(key=lambda x: x[1])