我有一张卡片等级和值的字典,我想对4张卡片进行排序,以便根据等级和值对卡片进行适当的排序。
RANKS = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"]
VALUES = [1, 2, 3, 4, 5, 6, 7, 8, 9 , 10, 10, 10, 10]
val_dict = dict(zip(RANKS, VALUES))
list = ["2","2","3","A"] # should sort to ["A",2,2,3]
list2 = ["10","K","J","Q"] # sort to [10,"J","Q","K"]
背景: 我想以这种方式对这些列表进行排序,以便计算在一个垃圾手中的运行。我使用卡的序数值来确定它们是否是连续的。 (我可以提供该代码,如果它可能有助于重新执行此操作)
答案 0 :(得分:3)
你已经掌握了它,你只需要使用你定义的val_dict
:
RANKS = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"]
VALUES = [1, 2, 3, 4, 5, 6, 7, 8, 9 , 10, 10, 10, 10]
val_dict = dict(zip(RANKS, VALUES))
现在只需在代码上添加使用val_dict
查找某个值的排名的代码......例如:
mylist = ["2","2","3","A"] # should sort to ["A",2,2,3]
mylist_sorted = sorted(mylist, key=val_dict.get)
# ['A', '2', '2', '3']
正如@Ashwini正确指出的那样,根据你的第二个例子,这不会产生所需的顺序。一个相当简单的方法来保持逻辑简单是改变值:
VALUES = [[1], [2], [3], [4], [5], [6], [7], [8], [9] , [10, 1], [10, 2], [10, 3], [10, 4]]
答案 1 :(得分:3)
假设您的列表一致(即['2', '2', '3', 'A']
)且由RANKS
的元素组成,则RANKS
中按位置排序就足够了:
>>> sorted(['2', '2', '3', 'A'], key=lambda x: RANKS.index(x))
['A', '2', '2', '3']
>>> sorted(['10',"K","J","Q"], key=lambda x: RANKS.index(x))
['10', 'J', 'Q', 'K']
或者,您可以使用
val_dict = dict(zip(RANKS, zip(VALUES, range(len(VALUES)))))
创建一个将RANK名称与其值及其索引相关联的字典。然后,您可以使用
进行简单排序sorted(myList, key=val_dict.get)
如建议的那样。
遵循相同的想法,但更简单,卡的实际等级可以放在这样的字典中
{k: v for v, k in enumerate(RANKS)}
更快的查找速度。同样,该值可以放在另一个dict中以便快速查找:
{RANKS[v]: k for v, k in enumerate(VALUES)}
答案 2 :(得分:1)
>>> VALUES = range(len(RANKS))
>>> val_dict = dict(zip(RANKS, VALUES))
>>> sorted([2,2,3,"A"], key=lambda x:val_dict[str(x)])
['A', 2, 2, 3]
>>> sorted([10,"K","J","Q"], key=lambda x:val_dict[str(x)])
[10, 'J', 'Q', 'K']