Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/visual-studio-2010/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何将第一个字母按特定顺序排序,第二个字母按其他特定顺序排序_Python - Fatal编程技术网

Python 如何将第一个字母按特定顺序排序,第二个字母按其他特定顺序排序

Python 如何将第一个字母按特定顺序排序,第二个字母按其他特定顺序排序,python,Python,我一直在想,当前两个字母都按特定顺序排列时,如何对列表进行排序。 基本上这是我的代码: Rank = '34567890JQKA2' Rank2 = 'DCHS' def sort(words): words.sort(key=lambda x: Rank.index(x[0])) words.sort(key=lambda x: Rank2.index(x[1])) return [words] print(sort['9C', '9H', '8H', '9D']) 这个函数的输出应

我一直在想,当前两个字母都按特定顺序排列时,如何对列表进行排序。 基本上这是我的代码:

Rank = '34567890JQKA2'
Rank2 = 'DCHS'
def sort(words):
  words.sort(key=lambda x: Rank.index(x[0]))
  words.sort(key=lambda x: Rank2.index(x[1]))
return [words]
print(sort['9C', '9H', '8H', '9D'])
这个函数的输出应该是升序的,所以

>>> ['8H','9D','9C','9H']

第4行按顺序对第一个字母进行排序,但不知道如何将第二个字母排序

您可以在lambda中设置多个参数进行排序

Ex:

Rank = '34567890JQKA2'
Rank2 = 'DCHS'
def sort_func(words):
    words.sort(key=lambda x: (Rank.index(x[0]), Rank2.index(x[1])))
    return words

print(sort_func(['9C', '9H', '8H', '9D']))
['8H', '9D', '9C', '9H']
输出:

Rank = '34567890JQKA2'
Rank2 = 'DCHS'
def sort_func(words):
    words.sort(key=lambda x: (Rank.index(x[0]), Rank2.index(x[1])))
    return words

print(sort_func(['9C', '9H', '8H', '9D']))
['8H', '9D', '9C', '9H']

排序
的键不需要是单个值-如果是多个值(在
元组
列表
中),将按顺序考虑它们

这里有一种方法,它甚至不限制您使用两个字符:

ranks = ['34567890JQKA2', 'DCHS']

data = ['9C', '9H', '8H', '9D']
data.sort(key=lambda x: [r.index(c) for r, c in zip(ranks, x)])
print(data)