Dogelike 发表于 2021-7-16 16:34:49

Python列表自定义排序问题求助

题目:扑克牌有四种花色:黑红梅方。扑克牌按点数从小到大是2,3,4,……,J,Q,K,A。编程序实现下列目标:
(1)按花色排序输出(小到大)
(2)按花色排序后,将同色牌按点数排序输出(大到小)
(3)第2步完成后,去除相同花色中数字重复的牌
下面是我的代码,感觉没什么问题,可就是运行之后毫无效果
importfunctools
Cards = ['梅花A','方块4','梅花2','方块4','红桃7','黑桃Q','红桃K','梅花9','方块9','红桃5','梅花J','方块8','红桃5','黑桃3','黑桃10','黑桃3','红桃7','黑桃Q']
def custom_cmp1(x, y):
    arr = ['黑桃','红桃','梅花','方块']
    if arr.index(x) < arr.index(y):
      return 1
    else:
      return -1
def StyleSort(*args):
    new = list(args)
    newlist = sorted(new,key=functools.cmp_to_key(custom_cmp1))
    return newlist
def custom_cmp2(x, y):
    arr = ['J','Q','K','A']
    if x == y:
      if arr.index(x) < arr.index(y):
            return 1
      else: return -1
def PointSort(*args):
    newlist = sorted(args,key=functools.cmp_to_key(custom_cmp2))
    return newlist
def DelRepeat(*args):
    for i in range(len(args)):
      for j in range(i+1,len(args)):
            if args == args:
                args = 'del'
    tmplist =
    newlist = list(tmplist)
    return newlist

Twilight6 发表于 2021-7-16 20:33:57


自己写了下,看看行不行达到需求:

from itertools import groupby

Cards = ['梅花A','方块4','梅花2','方块4','红桃7','黑桃Q','红桃K','梅花9','方块9','红桃5','梅花J','方块8','红桃5','黑桃3','黑桃10','黑桃3','红桃7','黑桃Q']
arr = ['黑桃','红桃','梅花','方块']
num = {'J':11, 'Q':12, 'K':13, 'A':14}

Cards.sort(key=lambda x:arr.index(x[:2]))
New_Cards = groupby(Cards,lambda x:x[:2])
New_Cards =

result = []
for i in range(len(New_Cards)):
    New_Cards.sort(key=lambda x: int(x) if x.isdigit() else num])
    ]

print(result)

Dogelike 发表于 2021-7-17 13:19:36

Twilight6 发表于 2021-7-16 20:33
自己写了下,看看行不行达到需求:

啊这,非常好,可是我看不懂{:10_282:}

Twilight6 发表于 2021-7-17 13:49:30

Dogelike 发表于 2021-7-17 13:19
啊这,非常好,可是我看不懂


代码中 [] 中括号中 for 循环就是列表推导式,第 13 行 lambad 匿名函数后面用的是 if -else 三目运算符

groupby 是分组函数,将同花色分组

qq1151985918 发表于 2021-7-17 15:31:55

Cards = ['梅花A','方块4','梅花2','方块4','红桃7','黑桃Q','红桃K','梅花9','方块9','红桃5','梅花J','方块8','红桃5','黑桃3','黑桃10','黑桃3','红桃7','黑桃Q']
arr = ['黑桃','红桃','梅花','方块']
num = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A']
all_cards =
res = sorted(set(Cards), key=all_cards.index)
print(res)
页: [1]
查看完整版本: Python列表自定义排序问题求助