Nic*_*ick 4 python sorting python-3.x
以下代码用于订购扑克手。它在Python 2.7中可以很好地工作,但在Python 3中却不起作用。已经进行了哪些更改,使其产生TypeError:不可排序的类型:tuple()<int()?
def poker(hands):
scores = [(i, score(hand.split())) for i, hand in enumerate(hands)]
winner = sorted(scores , key=lambda x:x[1])[-1][0]
return hands[winner]
def score(hand):
ranks = '23456789TJQKA'
rcounts = {ranks.find(r): ''.join(hand).count(r) for r, _ in hand}.items()
score, ranks = zip(*sorted((cnt, rank) for rank, cnt in rcounts)[::-1])
if len(score) == 5:
if ranks[0:2] == (12, 3): #adjust if 5 high straight
ranks = (3, 2, 1, 0, -1)
straight = ranks[0] - ranks[4] == 4
flush = len({suit for _, suit in hand}) == 1
'''no pair, straight, flush, or straight flush'''
score = ([1, (3,1,1,1)], [(3,1,1,2), (5,)])[flush][straight]
return score, ranks
>>> poker(['8C TS KC 9H 4S', '7D 2S 5D 3S AC', '8C AD 8D AC 9C', '7C 5H 8D TD KS'])
'8C AD 8D AC 9C'
Run Code Online (Sandbox Code Playgroud)
之所以发生是因为您正在比较int和tuple。在python2x中,cmp为不同的内置对象定义了默认操作,该对象已在python3中删除。
Python 3忽略了cmp()方法。除此之外,cmp()函数不见了!这通常会导致转换后的代码引发TypeError:不可排序的类型错误。因此,您需要用丰富的比较方法替换cmp()方法。为了支持排序,您只需要实现lt(),该方法用于“小于则”运算符<。
因此,在python2中,我们可以执行以下操作
(2, 3) > 2
Run Code Online (Sandbox Code Playgroud)
但它TypeError在python3中引发。如果此代码在python2中运行,则很可能是默认比较行为隐式处理的错误。
现在在您的示例中:
#value of scores that are being compared for sorting
scores = [(0, (1, (11, 8, 7, 6, 2))), (1, (1, (12, 5, 3, 1, 0))), (2, ((2, 2, 1), (12, 6, 7))), (3, (1, (11, 8, 6, 5, 3)))]
print(type(scores[1][1][0])) # <class 'int'>
print(type(scores[2][1][0])) # <class 'tuple'>
Run Code Online (Sandbox Code Playgroud)
正如我所解释的,它在python3中不起作用。什么是你承担一个比较的标准tuple和int。
如果您真的想比较不同类型的对象,则需要推出自己的版本tuple,然后在您的对象中使用该对象scores。
class MyTuple(tuple):
def __lt__(self, other):
pass
Run Code Online (Sandbox Code Playgroud)
注意:-我不建议使用这种方法。这只是出于教学目的。
| 归档时间: |
|
| 查看次数: |
8872 次 |
| 最近记录: |