简体   繁体   中英

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.

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

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:

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

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

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