|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
题目:扑克牌有四种花色:黑红梅方。扑克牌按点数从小到大是2,3,4,……,J,Q,K,A。编程序实现下列目标:
(1)按花色排序输出(小到大)
(2)按花色排序后,将同色牌按点数排序输出(大到小)
(3)第2步完成后,去除相同花色中数字重复的牌
下面是我的代码,感觉没什么问题,可就是运行之后毫无效果
import functools
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[0:1]) < arr.index(y[0:1]):
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[0:1] == y[0:1]:
if arr.index(x[2]) < arr.index(y[2]):
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[i] == args[j]:
args[j] = 'del'
tmplist = [e for e in args if e != 'del']
newlist = list(tmplist)
return newlist
自己写了下,看看行不行达到需求:
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 = [list(set(j)) for i,j in New_Cards]
result = []
for i in range(len(New_Cards)):
New_Cards[i].sort(key=lambda x: int(x[2:]) if x[2:].isdigit() else num[x[2]])
[result.append(j) for j in New_Cards[i]]
print(result)
|
|