将子列表排序为新的子列表? [英] Sorting sub-lists into new sub-lists?

查看:70
本文介绍了将子列表排序为新的子列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有很多两个成员的子列表,它们是名为mylist的列表的成员:

I have a large number of two-membered sub-lists that are members of a list called mylist:

mylist = [['AB001', 22100],
          ['AB001', 32935],
          ['XC013', 99834],
          ['VD126', 18884],
          ['AB001', 34439],
          ['XC013', 86701]]

我想根据子列表是否包含与第一项相同的字符串将mylist排序到新的子列表中.例如,这就是我要输出的代码:

I want to sort mylist into new sub-lists based on whether the sub-lists contain the same string as the first item. For example, this is what I am looking for my code to output:

newlist = [['AB001', 22100], ['AB001', 32935], ['AB001', 34439]],
          [['XC013', 99834], ['XC013', 86701]],
          [['VD126', 18884]]

这是我尝试编写此代码的方式:

Here is how I was trying to code this:

mylist = sorted(mylist)
newlist = []
for sublist in mylist:
    id = sublist[0]
if id == next.id:
    newlist.append(id)
print newlist

我还试图了解itertools.groupby()是否是解决此问题的正确工具.有人可以帮我解决这个问题吗?预先感谢.

I was also trying to understand if itertools.groupby() was the correct tool for this problem. Can someone help me with this problem? Thanks in advance.

推荐答案

请注意,您不能使用以前导零开头的十进制文字.我假设它实际上存储在变量中,所以没有前导零.

Note that you can't have decimal literals that start with a leading zero. I'll assume that this is actually stored in a variable so there is no leading zero.

您认为这是groupby的工作是正确的:

You were right about this being a job for groupby:

from itertools import groupby
from operator import itemgetter

mylist = [['AB001', 22100],
          ['AB001', 32935],
          ['XC013', 99834],
          ['VD126', 18884],
          ['AB001', 4439],
          ['XC013', 86701]]

print [list(value) for key, value in groupby(sorted(mylist), key=itemgetter(0))]

这将为您提供一个列表列表,按子列表中的第一项分组.

This will give you a list-of-lists, grouped by the first item in the sublist.

[[['AB001', 4439], ['AB001', 22100], ['AB001', 32935]], 
 [['VD126', 18884]], 
 [['XC013', 86701], ['XC013', 99834]]]

这篇关于将子列表排序为新的子列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆