繁体   English   中英

Python根据列表中的索引在列表中创建新列表

[英]Python create new lists within a list based on the index within a list

如果我有名单

a = ['1 2 3 4 5', '1 2 3 4 etc', '1 etc etc', '2 5 6 8', '2 7 3 9', '2 etc etc']

我希望能够根据每个元素开始的内容对其进行排序。 所以我想要的输出是:

a = [['1 2 3 4 5', '1 2 3 4 etc', '1 etc etc'], ['2 5 6 8', '2 7 3 9', '2 etc etc']]

但问题是,对于我的真实代码,我不知道有很多字符串以“1”或“2”开头,因此我无法根据固定值划分列表,有没有办法比较每个元素并组合它们,如果它们相同?

您可以将itertools.groupby()与列表理解结合使用:

>>> import itertools
>>> a = ['1 2 3 4 5', '1 2 3 4 etc', '1 etc etc', '2 5 6 8', '2 7 3 9', '2 etc etc']
>>> [list(x[1]) for x in itertools.groupby(a, lambda i: i.split(" ")[0])]
[['1 2 3 4 5', '1 2 3 4 etc', '1 etc etc'], ['2 5 6 8', '2 7 3 9', '2 etc etc']]

请注意, .groupby()需要对可迭代对象(即a )进行排序,因此如果您的真实数据看起来不同,您可能必须先对其进行排序。

这在不使用任何包的情况下工作,并且与对象的类型无关,第 0 个元素可能是:

a = ['1 2 3 4 5', '1 2 3 4 etc', '1 etc etc', '2 5 6 8', '2 7 3 9', '2 etc etc']

already_sorted = []
new_a = []

for i in range(0, len(a)):
    if i in already_sorted:
        continue
    else:
        tmp = []
        for j in range(0, len(a)):

            if a[i][0] == a[j][0] and j not in already_sorted:
                tmp.append(a[j])
                already_sorted.append(j)

        new_a.append(tmp)

print(new_a)

输出:

[['1 2 3 4 5', '1 2 3 4 etc', '1 etc etc'], ['2 5 6 8', '2 7 3 9', '2 etc etc']]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM