【发布时间】:2017-12-04 04:10:59
【问题描述】:
我有点卡在一个家庭作业问题上。 假设我有一个这样的列表:
[('Paul George', 1), ('Luke Skywalker', 2), ('Mitchell Piker', 3), ('Phil Dam', 1)]
我必须编写一个函数,使列表按第二个元素(即整数值)排序。另外,如果两个人的整数相同,那么我必须按字母顺序排序。另外,我可以使用sort,但我不能使用可选参数key。所以我应该有这样的东西:
[('Mitchell Piker', 3), ('Luke Skywalker', 2), ('Paul George', 1), ('Phil Dam', 1)]
>>> def sort(lst: List[Tuple[str, int]]):
"""Return the list of tuples from largest integer score to lowest
integer score. If two people have the same score, then sort them by
alphabetical order.
"""
lst2 = []
lst2.append(lst[0])
for i in range(len(lst)):
for j in range(len(lst2)):
if lst[i][-1] > lst2[j][-1] and lst[i][-1] not in lst2:
lst2.insert(0, lst2[i])
if lst[i][-1] < lst2[j][-1] and lst[i][-1] not in lst2:
lst2.append(lst2[i][-1])
return lst2
但是我得到一个错误。任何人都可以帮忙吗?非常感谢
【问题讨论】:
-
lst: List(Tuple(str, int))? -
@alfasin 后来注意到了。已经删除了。 :)。
-
“我收到一个错误”请在您的帖子中分享该错误...
标签: python list sorting for-loop tuples