【问题标题】:Function that sorts multiple arguments [duplicate]对多个参数进行排序的函数[重复]
【发布时间】:2020-09-19 12:55:51
【问题描述】:

我需要编写一个函数sort_gradebook(gradebook),它有下一个参数:[first_name, last_name, grade_1, grade_2, ..., grade_n, final_grade]。函数必须排序:

  • 期末成绩
  • 如果最终成绩相同 - 一年级
  • 如果一年级相等 - 通过二年级等
  • 如果所有成绩都相同 - 按第二个名字
  • 如果第二名相同 - 按名称。

我能做的一切:

from operator import itemgetter

def sort_gradebook(*gradebook):
    length = len([str(i) for i in gradebook[0]])
    a = [i for i in range(length)]
    for i in a:
        s = sorted(gradebook, key = itemgetter(i))

    return s

测试用:

from itertools import permutations

def test_sort(inp, outp):
    for i in permutations(inp):
        assert sort_gradebook(list(i)) == outp

test_sort([['Alice', 'Smith', 2, 3, 4],
    ['John', 'Smith', 2, 3, 5]], [['John', 'Smith', 2, 3, 5],
    ['Alice', 'Smith', 2, 3, 4]
])

【问题讨论】:

  • 那么,成绩的数量可以改变吗?
  • 你错过了reverse,因为约翰的期末成绩更高并且排在第一
  • @Mandera 不,不是。我已经看到了那些答案。它们适用于 2 个论点,但不适用于更多论点……或者我不知道如何将它用于多个论点……无论如何,如果有人可以解释,我将不胜感激,如何应用该答案我的问题。
  • @SultanTapi 哦,好吧,我知道你怎么能这么想。你错过的是sortkey 参数可以处理一个元组,这意味着你可以有无限的键,而不仅仅是他们在示例中使用的两个。

标签: python python-3.x code-inspection


【解决方案1】:

排序

  • 您想对多个参数进行排序,即不同的索引。你可以使用itemgetter(0,1,2),在你的情况下itemgetter(4,3,2,1,0)需要根据大小动态构建

  • 添加reverse=True,让最终成绩较高的John排在Alice之前

def sort_gradebooks(*gradebooks):
    nb_attributes = len(gradebooks[0])
    s = itemgetter(*[i for i in range(nb_attributes - 1, -1, -1)]) # itemgetter(4,3,2,1,0)
    return sorted(gradebooks, key=s, reverse=True)

叫它

您需要使用*ii 调用排序来传递展平参数,而不是传递一个列表,而是传递多个项目

def test_sort(inp, outp):
    for i in permutations(inp):
        print(sort_gradebooks(*i) == outp)

print(sort_gradebooks(*[['Alice', 'Smith', 2, 3, 4], ['John', 'Smith', 2, 3, 5]])) # John / Alice because final grade
print(sort_gradebooks(*[['Alice', 'Smith', 2, 3, 5], ['John', 'Smith', 2, 3, 5]])) # John / Alice because name
print(sort_gradebooks(*[['Alice', 'Smith', 2, 5, 5], ['John', 'Smith', 2, 3, 5]])) # Alice / John because 2ng grade

【讨论】:

  • 谢谢!漂亮的代码!能否解释一下,itemgetter(4,3,2,1,0) 从 ind(4) 开始排序?
  • @SultanTapi 0,1,2,3,4 是['Alice', 'Smith', 2, 3, 4]每个值的索引
  • 我知道。 s = itemgetter(*[i for i in range(nb_attributes - 1, -1, -1)]) # itemgetter(4,3,2,1,0) - 从索引 4 开始排序,然后是 3, 2, 1和 0?
  • @SultanTapi 是的
  • 谢谢!最后一个问题:我在某处读到,如果你想按几个参数排序,你必须从最早到最晚开始,例如在 ['Alice', 'Smith', 1, 3, 5], ['John' , 'Smith', 2, 3, 5], 首先必须按 ind(0), then(1) 等排序对吗?如果是,你的排序是如何工作的,如果它从 ind(4) 开始?
猜你喜欢
  • 2013-02-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-18
  • 2016-02-27
相关资源
最近更新 更多