【问题标题】:sorted() function on python for tuplepython上用于元组的sorted()函数
【发布时间】:2022-01-05 19:24:45
【问题描述】:

在这段代码中,必须对元组进行排序,但我问用户想要什么样的排序,但这个问题被问了四次:

students = (("st_1", "a", "40"),
            ("st_2", "b", "38"),
            ("st_3", "c", "32"),
            ("st_4", "a", "10"))
def key_sort(keys):
    index = 0
    what_sort = input("do you sort a list ? n for name , g for grade and a for age : ").lower()
    if what_sort == 'a':
        index = keys[2]
    elif what_sort == 'n':
        index = keys[0]
    elif what_sort == 'g':
        index = keys[1]
return index        

sorted_students = sorted(students, key=key_sort)
for i in sorted_students:    
    print(i)

为什么要问四次? terminal result

【问题讨论】:

  • 因为 key_sort 会为列表中的每个项目调用...
  • 预先输入并调用函数,然后将值传递给排序

标签: python function sorting tuples


【解决方案1】:

先询问,然后构造一个适当的函数传递给sorted

from operator import itemgetter

what_sort = input("do you sort a list ? n for name , g for grade and a for age : ").lower()

if what_sort == 'a':
    n = 2
elif what_sort == 'n':
    n = 0
elif what_sort == 'g':
    n = 1
else:
    n = 0  # Pick a good default      


sorted_students = sorted(students, key=itemgetter(n))

【讨论】:

  • n = {"a": 2, "n": 0, "g": 1}.get(what_sort, 0),仍然+1
  • 一个小成本,但我想避免构建一个 dict 的成本只索引一次。当然,这里我是在重复比较what_sort,而不是单个哈希操作。我不知道盈亏平衡点 X 在哪里(少于 X 选择,使用 if-elif 链;多于 X,索引 dict
  • 我认为这只会混淆 OP。如果他们不明白如何使用key,你凭什么认为他们会理解itemgetter?至少你应该解释一下这个函数是如何工作的。
  • 他们不需要了解itemgetter(首先并不难理解:itemgetter(n) == lambda x: x[n])。
【解决方案2】:

key=key_sort 表示对于每个项目keysorted() 函数将调用key_sort(key) 来确定该键的排序顺序。您在该函数中有一个 input(),如果列表中有 4 个项目,这意味着 key_sort() 将被调用 4 次。它只是 Python 按设计工作。如果您希望输入不是每次都运行,则必须使用某种条件。或者,更有意义的是事先询问排序方法,然后设置key_sort 然后使用的类或全局变量what_sort

【讨论】:

    【解决方案3】:

    正如@Joran Beasley 指出的那样,sorted 中的key 参数被调用到要排序的迭代中的每个元素(在您的情况下,变量students)。

    获得您所要求的行为的一种方法是修改key_sort 函数以返回另一个函数,该函数应该用作key 调用中的key 参数。

    请考虑以下代码

    students = (("st_1", "a", "40"),
                ("st_2", "b", "38"),
                ("st_3", "c", "32"),
                ("st_4", "a", "10"))
    
    def key_sort():
        index = 0
        what_sort = input("do you sort a list ? n for name , g for grade and a for age : ").lower()
        if what_sort == 'a':
            index = 2
        elif what_sort == 'n':
            index = 0
        elif what_sort == 'g':
            index = 1
        return lambda student: student[index]
    
    key_fn = key_sort()
    sorted_students = sorted(students, key=key_fn)
    for i in sorted_students:    
        print(i)
    

    这样,用户交互(input 函数调用)将只运行一次。

    【讨论】:

      【解决方案4】:

      sorted 函数中的key 参数是用于获取要排序的值的函数的名称。例如,在整数列表中,这是不必要的,因为当然可以直接比较和排序对象本身。但是对于元组,尚不清楚应该如何比较它们。使用第一个元素?最后一个?所有这些的哈希? Python 无法回答这个问题。 key 存在,因此您可以指定如何操作。

      您的特定问题的解决方案是首先询问用户问题,然后使用他们的答案来选择如何对列表进行排序。有很多方法可以做到这一点,但这是我认为最简单的方法。

      students = (("st_1", "a", "40"),
                  ("st_2", "b", "38"),
                  ("st_3", "c", "32"),
                  ("st_4", "a", "10"))
      
      def get_name(student):
          return student[0]
      
      def get_grade(student):
          return student[1]
      
      def get_age(student):
          return student[2]
      
      sort_index = input("How should the list be sorted? (n for name , g for grade and a for age) : ").lower()
      
      if sort_index == 'n':
          sorted_students = sorted(students, key=get_name)
      elif sort_index == 'g':
          sorted_students = sorted(students, key=get_grade)
      elif sort_index == 'a':
          sorted_students = sorted(students, key=get_age)
      else:
          print('Unsupported option')
          exit(1)
      
      print(sorted_students)
      

      【讨论】:

        猜你喜欢
        • 2013-10-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-01-04
        • 1970-01-01
        • 2014-01-30
        • 2012-02-04
        • 2015-04-12
        相关资源
        最近更新 更多