大家好,我正在努力编写一个对数字进行排名的函数。该代码可以正常工作,但有两点效果不佳。我们知道如果两个数字相同,它们将获得相同的位置(或排名),但是根据我的代码,两个相同的数字具有不同的排名。同样,当到达21st时,代码将打印21th而不是21st。我该如何解决这个问题。此代码
a = [20,50,67,100,93,89,72,81,79,66,49,73,29,50,52,69,71,70,71,84,67]
def ranker(zed):
prefixes = ["st", "nd", "rd" ,"th"]
zed.sort(reverse =True)
found = [ ]
for dig in zed:
pre = len(found) + 1
if len(found) > 3:
found.append(str(dig) + " " + str(pre) + prefixes[ 3 ])
else:
found.append(str(dig) + " " + str(pre) + prefixes[ len(found) ])
print(found)
ranker(a)
答案 0 :(得分:1)
更简单的
首先,我们找到重复的条目,并存储每个重复条目的出现次数,以便稍后可以使用它多次追加必要的条目。
要处理正确的前缀,我们创建了前20个元素的列表。如果位置> 20,我们将重用前10个。
注意:在我的代码中查找重复项并不是很有效。我们可以在这里改用 Counter (也许这会更好)
a =[20,50,67,100,93,89,72,81,79,66,49,73,29,50,52,69,71,70,71,84,67]
def ranker(zed):
#prefixes = ["st", "nd", "rd", * ["th"] * 17]
prefixes = ["st", "nd", "rd"] + [ "th" for _ in range(17) ]
duplicates = {x : zed.count(x) for x in zed if zed.count(x) > 1}
zedset = sorted(set(zed))
found = [ ]
for count, dig in enumerate(reversed(zedset),1):
z = 20 if count % 100 <= 20 else 10
occurs = duplicates.get(dig , 1)
for _ in range(occurs):
found.append(str(dig) + " " + str(count) + prefixes[(count - 1) % z])
print(found)
答案 1 :(得分:0)
我相信这就是你想要的。
a = [20,50,67,100,93,89,72,81,79,66,49,73,29,50,52,69,71,70,71,84,67]
def ranker(zed):
prefixes = ["st", "nd", "rd" ,"th"]
zed.sort(reverse =True)
found = [ ]
for dig in zed:
pre = len(found) + 1
if found and dig==int(found[-1].split(' ')[0]):
found.append(found[-1])
else:
if pre > 3:
if pre>20 and pre%10<3 and pre%100<10 or pre%100>20:
found.append(str(dig) + " " + str(pre) + prefixes[len(found)%10])
else:
found.append(str(dig) + " " + str(pre) + prefixes[ 3 ])
else:
found.append(str(dig) + " " + str(pre) + prefixes[len(found)])
print(found)
ranker(a)