我有
iList = [('FirstParam', 1), ('FirstParam', 2),
('FirstParam', 3), ('FirstParam', 4),
('SecondParam', 5), ('SecondParam', 6),
('SecondParam', 7)]
我正在努力形成:
iList1 = [('FirstParam', 1), ('FirstParam', 2),
('FirstParam', 3), ('FirstParam', 4)]
iList2 = [('SecondParam', 5), ('SecondParam', 6),
('SecondParam', 7)]
我试过了:
for key, group in itertools.groupby(iList, operator.itemgetter(0)):
print "List",(list(group))
它以我想要的方式打印2个列表。 输出:
List [('FirstParam', 1), ('FirstParam', 2),
('FirstParam', 3), ('FirstParam', 4)]
List [('SecondParam', 5), ('SecondParam', 6),
('SecondParam', 7)]
我担心的是我应该如何制作iList1和iList2?
我没有按照(list(group))
的方式工作并打印列表。
答案 0 :(得分:0)
您可以使用列表理解并解压缩到iList1
和iList2
:
iList1, iList2 = [list(group) for key, group in itertools.groupby(iList, operator.itemgetter(0))]
然后你会得到你想要的东西:
>>> iList1
[('FirstParam', 1), ('FirstParam', 2), ('FirstParam', 3), ('FirstParam', 4)]
>>> iList2
[('SecondParam', 5), ('SecondParam', 6), ('SecondParam', 7)]