I have a list a = ['a1', 'b1', 'c1', 'd1', 'a2', 'b2', 'c2', 'd2',]
How can I get list b = ['a1,', 'a2', 'b1', 'b2', 'c1', 'c2', 'd1', 'd2'] without using .sorted()?
Thanks!
I have a list a = ['a1', 'b1', 'c1', 'd1', 'a2', 'b2', 'c2', 'd2',]
How can I get list b = ['a1,', 'a2', 'b1', 'b2', 'c1', 'c2', 'd1', 'd2'] without using .sorted()?
Thanks!
There is no .sorted() method for lists, though there is the sorted() function, as S.Mark pointed out (which returns a new sorted list), and a .sort() method (which sorts a list in place and returns None). If you meant to not use the sorted() function, then:
a = ['a1', 'b1', 'c1', 'd1', 'a2', 'b2', 'c2', 'd2',]
a.sort()
b = a
otherwise, maybe you can clarify your question further.
It seems a bit arbitrary, not to use sorted(). I think you mean, that you don't want to sort the list in the (default) alphanumerical order.
Here is how you define a key for sorting strings that represent playing cards (a1 through d13) by suit, then rank:
>>> def cardsortkey(card):
... return (card[0], int(card[1:]))
...
>>> cardsortkey('a1')
('a', 1)
>>> a = ['a1', 'b1', 'c1', 'd1',
... 'a2', 'b2', 'c2', 'd2',
... 'a11', 'b11', 'c11', 'd11']
>>> sorted(a, key=cardsortkey)
['a1', 'a2', 'a11', 'b1', 'b2', 'b11', 'c1', 'c2', 'c11', 'd1', 'd2', 'd11']
Is that what you need?
without using sorted, but expensive way.
a = ['a1', 'b1', 'c1', 'd1', 'a2', 'b2', 'c2', 'd2',]
split it to 2 parts
['a1', 'b1', 'c1', 'd1',] ['a2', 'b2', 'c2', 'd2',]
zip it
[('a1', 'a2'), ('b1', 'b2'), ('c1', 'c2'), ('d1', 'd2')]
and flatten it (with itertools here)
import itertools
itertools.chain(*zip(a[:len(a)/2],a[len(a)/2:]))
itertools returns iterator, so If you need list, wrapped it with list(), and assigned it to b
b = list(itertools.chain(*zip(a[:len(a)/2],a[len(a)/2:])))
=> ['a1', 'a2', 'b1', 'b2', 'c1', 'c2', 'd1', 'd2']
just b = sorted(a) ?
sorted(), so posted this, but I have no idea now.l = ['a1', 'b1', 'c1', 'd1', 'a2', 'b2', 'c2', 'd2']
numbersPerLetter = 2
lsorted = []
for i in range(len(l) / numbersPerLetter):
lsorted.extend([l[x+i] for x in range(0, len(l), len(l) / numbersPerLetter)])
print(lsorted)
Output:
['a1', 'a2', 'b1', 'b2', 'c1', 'c2', 'd1', 'd2']
In Python 3.X you have to change / to // in order to make it work.