简体   繁体   English

如何在Python中对该数组排序?

[英]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): 我尝试通过这种方式进行操作(five_cards_num是数组的名称):

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' TypeError:“ int”和“ 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: 您可以使用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']

Again another approach using itertools . 还是使用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']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM