简体   繁体   中英

Python create new lists within a list based on the index within a list

If I have the 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']

I want to be able to sort this based on what each element starts on. So the output I want is:

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']]

But the thing is, for my real code, I won't know have many strings starts with a '1' or with a '2', so therefore I can't divide the list based on a fixed value, is there a way of comparing each element and combine them if they're the same?

You can use itertools.groupby() combined with a list comprehension:

>>> 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']]

Note that .groupby() requires the iterable (ie a ) to be sorted, so you may have to sort it first if your real data looks different.

This works without using any package and independently of the type of object the 0th element may be:

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)

Output:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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