Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby-on-rails-4/2.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_Python 3.x_List_Sorting - Fatal编程技术网

如何按另一个列表对列表进行排序';Python中的索引号是多少?

如何按另一个列表对列表进行排序';Python中的索引号是多少?,python,python-3.x,list,sorting,Python,Python 3.x,List,Sorting,在Python中按值对字典排序时,我们使用lambda func。但我在列表中尝试了这种方法,而不是使用另一个列表索引号。对于我的问题,这可能是一个简短的str函数/方法 以下是一个例子: cardsorder = ['2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A'] colors = ['C', 'D', 'S', 'H'] handEx = ['8C','TS','KC','9H','4S'] 我想使用cards

在Python中按值对字典排序时,我们使用lambda func。但我在列表中尝试了这种方法,而不是使用另一个列表索引号。对于我的问题,这可能是一个简短的str函数/方法

以下是一个例子:

cardsorder = ['2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A']
colors = ['C', 'D', 'S', 'H']
handEx = ['8C','TS','KC','9H','4S']
我想使用
cardsorder
索引编号对我的
handEx
列表元素进行排序。 首先,我扫描每个元素,找到要排序的值:

for card in handEx:
    value = cardsorder.index(card[0])
通过使用这些值,我可以通过比较其他值对元素进行排序,但我认为要找到解决方案还有很长的路要走。
是否有更简单的解决方案,例如使用lambda函数?

您非常接近。只需创建一个键函数,该函数获取的值与
值相当:

>>> sorted(handEx, key=lambda card: cardsorder.index(card[0]))
['4S', '8C', '9H', 'TS', 'KC']
或在适当的地方:

handEx.sort(key=lambda card: cardsorder.index(card[0]))
顺便说一下,我发布了一个类似的答案