Python .sort()无法按预期工作 [英] Python .sort() not working as expected
问题描述
在一个安静的星期六晚上解决一些拼图问题(woohoo……不是),并且正在与sort()挣扎.结果并不完全符合我的期望.该程序从100到999的每个组合中进行迭代,并检查产品是否为回文器.如果是这样,请追加到列表中.我需要对列表进行排序:D这是我的程序:
Tackling a few puzzle problems on a quiet Saturday night (wooohoo... not) and am struggling with sort(). The results aren't quite what I expect. The program iterates through every combination from 100 - 999 and checks if the product is a palindome. If it is, append to the list. I need the list sorted :D Here's my program:
list = [] #list of numbers
for x in xrange(100,1000): #loops for first value of combination
for y in xrange(x,1000): #and 2nd value
mult = x*y
reversed = str(mult)[::-1] #reverses the number
if (reversed == str(mult)):
list.append(reversed)
list.sort()
print list[:10]
哪个网:
['101101', '10201', '102201', '102201', '105501', '105501', '106601', '108801',
'108801', '110011']
显然索引0大于1.知道发生了什么吗?我觉得这跟尾随/前导零有关,但是我快速浏览了一下,看不到问题所在.
Clearly index 0 is larger then 1. Any idea what's going on? I have a feeling it's got something to do with trailing/leading zeroes, but I had a quick look and I can't see the problem.
奖励积分,如果您知道谜题来自哪里:P
Bonus points if you know where the puzzle comes from :P
推荐答案
您正在对字符串而不是数字进行排序. '101101' < '10201'
,因为'1' < '2'
.将list.append(reversed)
更改为list.append(int(reversed))
,它将起作用(或使用其他排序功能).
You are sorting strings, not numbers. '101101' < '10201'
because '1' < '2'
. Change list.append(reversed)
to list.append(int(reversed))
and it will work (or use a different sorting function).
这篇关于Python .sort()无法按预期工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!