Reputation: 227
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??
Upvotes: 1
Views: 3245
Reputation: 1882
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
Upvotes: 1
Reputation: 34017
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)
;)
Upvotes: 5
Reputation: 137438
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))
Upvotes: 3