所以,我有这段代码:
umw = {'T':10, 'J':11, 'Q':12, 'K':13, 'A':14}
def card_ranks(ranks):
"Return a list of the ranks, sorted with higher first."
for i in ranks:
if i in umw:
index = ranks.index(i)
ranks[index] = str(umw[i])
ranks.sort(reverse = True)
return ranks
print(card_ranks(['A', '3', '4', 'K'])) #should output [14, 13, 4, 3]
这给了我以下结果:
['4', '3', '14', '13']
清除“reverse = True”会产生以下结果:
['13', '14', '3', '4']
如果我这样做的话:
r = card_ranks(['A', '3', '4', 'K'])
r[0] -> gives me '4'
but this doesnt work again:
print(sorted(r)) -> gives me ['4', '3', '14', '13'] all over again.
看来,.sort()命令可以查看13& 14作为一个单位和3& 4.
有人可以解释为什么会这样吗?
非常感谢!
答案 0 :(得分:6)
您按字典顺序对它们进行排序,如字符串而不是数字。您可以先将它们转换为整数,也可以展开umw
字典:
umw = {str(i): i for i in range(2, 10)}
umw.update({'T':10, 'J':11, 'Q':12, 'K':13, 'A':14})
def card_ranks(ranks):
return sorted(ranks, key=umw.get, reverse=True)
card_ranks(['A', '3', '4', 'K'])
# ['A', 'K', '4', '3']
这会将dict.get
方法用作key function来指导排序,而不会更改要排序的值。
答案 1 :(得分:3)
您正在排序'11'
'3'
之前的字符串。以下sorted
调用涉及必要的类型转换:
def card_ranks(ranks):
return sorted((umw[c] if c in umw else int(c) for c in ranks), reverse=True)
>>> card_ranks(['A', '3', '4', 'K'])
[14, 13, 4, 3]
对于ranks
中的每个字符串,生成器表达式在umw
dict中生成相应的值,或者作为回退,将字符串转换为int
,这样一个正确的数字,可以进行非词典编纂比较。
答案 2 :(得分:1)
它没有将它们视为一个单元,它比较了charakter的charakter:
'1'<'3'<'4'
,因此排名为'13'<'14'<'3'<'4'
您希望所有这些都是数字,因此请更改以下行:
ranks[index] = str(umw[i])
到
ranks[index] = umw[i]
和
print(card_ranks(['A', '3', '4', 'K']))
到
print(card_ranks(['A', 3, 4, 'K']))
答案 3 :(得分:1)
这意味着"233" < "3"
和"1111" < "233"
umw = {'T':10, 'J':11, 'Q':12, 'K':13, 'A':14}
def card_ranks(ranks):
"Return a list of the ranks, sorted with higher first."
for i in ranks:
if i in umw:
index = ranks.index(i)
ranks[index] = str(umw[i])
ranks = list(map(int, ranks)) # The line to be added
ranks.sort(reverse = True)
return ranks
print(card_ranks(['A', '3', '4', 'K'])) #sh
ranks = list(map(int, ranks))
将列表元素转换为int
答案 4 :(得分:0)
ranks[index] = str(umw[i])
您将值保存为字符串而不是整数。它将它们分类为字符串。
尝试
ranks[index] = int(umw[i])