How do I sort this array in Python?

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



How do I sort this array in Python?



I have this array:


[14, 'S', 12, 'D', 8, 'S', 9, 'S', 10, 'D']



I want to sort it in descending order (numbers), but at the same time keep the number with the following letter together. So the result should look like this:


[14, 'S', 12, 'D', 10, 'D', 9, 'S', 8, 'S']



How can I do this?



I tried to do it this way (five_cards_num is the name of the array):


for j in range(4):
max = five_cards_num[j]
max_color = five_cards_num[j+1]
for i in range(j, 5):
if (five_cards_num[2*i] > max):
max = five_cards_num[2*i]
max_color = five_cards_num[2*i+1]
five_cards_num[2*i] = five_cards_num[j]
five_cards_num[2*i+1] = five_cards_num[j+1]
five_cards_num[j] = max
five_cards_num[j+1] = max_color



But I get error:



TypeError: '>' not supported between instances of 'int' and 'str'



Thank you in advance.




3 Answers
3



You can use zip to turn the list into a list of tuples so you can sort the pairs together, and then flatten it with nested list comprehension afterwards:


zip


print([a for i in sorted(zip(five_cards_num[::2], five_cards_num[1::2]), reverse=True) for a in i])



This outputs:


[14, 'S', 12, 'D', 10, 'D', 9, 'S', 8, 'S']





Works perfectly, thanks! Could you please give me a little more explanation on what "a for i in" and "for a in i" does? I've never seen "for" used like this before.
– Andrej
Aug 8 at 13:08





Glad to be of help. You can refer to nested list comprehension for more details.
– blhsing
Aug 8 at 13:32



I prefer this simple solution:


list(sum(sorted(zip(x[::2], x[1::2]), reverse=True), ()))



Output:


[14, 'S', 12, 'D', 10, 'D', 9, 'S', 8, 'S']





Nice one liner :) @Lev
– Kostadin Slavov
Aug 8 at 11:45





@KostadinSlavov Thanks:)
– Lev Zakharov
Aug 8 at 11:48



Again another approach using itertools.


>>> import itertools as it
>>> a = [14, 'S', 12, 'D', 8, 'S', 9, 'S', 10, 'D']
>>> b = sorted(it.izip(*[iter(a)]*2), reverse=True)
>>> b
[(14, 'S'), (12, 'D'), (10, 'D'), (9, 'S'), (8, 'S')] # you may want to play with a list of tuples (?|!)
>>> list(it.chain(*b))
[14, 'S', 12, 'D', 10, 'D', 9, 'S', 8, 'S']






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Firebase Auth - with Email and Password - Check user already registered

Dynamically update html content plain JS

How to determine optimal route across keyboard