【问题标题】:how to sort nested list without using optional argument `key`如何在不使用可选参数“key”的情况下对嵌套列表进行排序
【发布时间】: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


【解决方案1】:

如果可以假设数字总是整数,您可以使用它们来索引值,就像这样(也可以通过排序而不是排序来实现)

groups = defaultdict(list)
max_id = -1
for name, idx in lst:
    groups[idx].append(name)
    if max_id < idx:
        max_id = idx
result = [(name, idx) for idx in range(max_id, -1, -1) for name in sorted(groups.get(idx, []))]
# [('Mitchell Piker', 3), ('Luke Skywalker', 2), ('Paul George', 1), ('Phil Dam', 1)]

编辑:

from collections import defaultdict
groups = defaultdict(list)
for name, idx in lst:
    groups[idx].append(name)
[(name, idx) for idx in sorted(groups.keys())[::-1] for name in sorted(groups[idx])]

注意:如果您反对使用groups.keys(),您可以随时使用[x for x in groups]...

【讨论】:

  • 小修改将使它可以处理任何数字(不仅仅是int),而且可以说是更干净的方式:见编辑
【解决方案2】:

假设函数的签名只是在问题中搞砸了(否则代码将引发NameError

问题是因为这行:

for j in range(len(lst2))

lst2 的长度为零 - 永远不会执行循环...

【讨论】:

  • 对不起,我忘了输入 lst2.append(lst[0])。该问题已被编辑。很抱歉造成混乱
  • @DWCY 不会改变问题
【解决方案3】:

那又怎样?

lst = [('Paul George', 1), ('Luke Skywalker', 2), ('Mitchell Piker', 3), ('Phil Dam', 1)]

[(n,-i) for (i,n) in sorted([(-i,n) for (n,i) in lst])]


[('Mitchell Piker', 3),
 ('Luke Skywalker', 2),
 ('Paul George', 1),
 ('Phil Dam', 1)]

解释:sorted 做你想做的事,除了:

  • 它将首先根据第一个元素(名称)进行排序

  • 然后根据第二个元素(数字)排序,但也按升序排列

所以要解决这个问题:将它与元素交换以及否定数字夹在中间。

【讨论】:

    【解决方案4】:

    你可以试试这样的:

    仅针对 test_case,为了更准确,我已经编辑了名称:

    your_data=[('Paul George', 1), ('Luke Skywalker', 2), ('Mitchell Piker', 3), ('Ahil Dam', 1)]
    
    new={}
    for item in your_data:
        if item[1] not in new:
            new[item[1]]=[item[0]]
        else:
            new[item[1]].append(item[0])
    
    
        for key,value in new.items():
            if len(value)>1:
    
                new[key]=sorted(value)
    
    
    
    final_list=[]
    for key,value in new.items():
        if len(value) > 1:
            for sub_item in value:
                final_list.append((sub_item,key))
        else:
            final_list.append(("".join(value),key))
    
    
    print(final_list)
    

    输出:

    [('Ahil Dam', 1), ('Paul George', 1), ('Luke Skywalker', 2), ('Mitchell Piker', 3)]
    

    或者如果你想要这样的结果,那么只需反转最终结果:

    print(final_list[::-1])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-07-27
      • 1970-01-01
      • 2014-06-25
      • 2021-09-25
      • 2015-08-12
      • 1970-01-01
      • 2017-10-09
      • 1970-01-01
      相关资源
      最近更新 更多