Skip to content Skip to sidebar Skip to footer

Sort Lines In A String, Group Data

I'm trying to group string like a map output. Ex: String = ' a,a a,b a,c b,a b,b b,c' Op: a a,b,c b a,b,c Is this kind of output possible in a single step

Solution 1:

use the builtin sorted:

In [863]: st=sorted(String.split())
Out[863]: ['aa', 'ab', 'ba', 'bb']

to print it:

In [865]: print'\n'.join(st)
aa
ab
ba
bb

list.sort sorts the list in place and returns None, that's why when you print(lines.sort()) it shows nothing! show your list by lines.sort(); prnit(lines) ;)

Solution 2:

Note that list.sort() sorts the list in-place, and does not return a new list. That's why

print(lines.sort())

is printing None. Try:

lines.sort()    # This modifies lines to become a sorted version
print(lines)

Alternatively, there is the built-in sorted() function, which returns a sorted copy of the list, leaving the original unmodified. Use it like this:

print(sorted(list))

Solution 3:

Because so far the other answers focus on sorting, I want to contribute this for the grouping issue:

String = """
    a a
    a b
    a c
    b a
    b b
    b c"""

pairs = sorted(line.split() for line in String.split('\n') if line.strip() )

from operator import itemgetter
from itertools import groupby
for first, grouper in groupby(pairs, itemgetter(0)):
    print first, "\t", ', '.join(second for first, second in grouper)

Out:
a   a, b, c
b   a, b, c

Post a Comment for "Sort Lines In A String, Group Data"