简体   繁体   中英

sorting the list in Python without .sorted()

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

只是b = sorted(a)

You can also sort it this way

for i1, e1 in enumerate(a):
   for i2, e2 in enumerate(a):
      if e2 > e1:
         e1 = a[i2]
         a[i2] = a[i1]
         a[i1] = e1
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.

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