【问题标题】:sorting a tuple that contains string and numbers in python在python中对包含字符串和数字的元组进行排序
【发布时间】:2019-11-17 15:45:27
【问题描述】:

我有一个这样的清单;

List = [('apple 5', 12), ('apple 3', 2), ('apple 6', 10),('apple 4', 15), ('apple 9', 11), ('apple 7', 14), ('apple 18', 10), ('apple 16', 10),('orange 5', 4), ('orange 4', 7)]

我知道如何正常排序列表。

for i in sorted(List):
  print(i)

这给了;

('apple 16', 10)
('apple 18', 10)
('apple 3', 2)
('apple 4', 15)
('apple 5', 12)
('apple 6', 10)
('apple 7', 14)
('apple 9', 11)
('orange 4', 7)
('orange 5', 4)

但是我可以这样排序吗?

('apple 3', 2)
('apple 4', 15)
('apple 5', 12)
('apple 6', 10)
('apple 7', 14)
('apple 9', 11)
('apple 16', 10)
('apple 18', 10)
('orange 4', 7)
('orange 5', 4)

【问题讨论】:

    标签: python arrays python-3.x list tuples


    【解决方案1】:

    你只需要分配你自己的key

    l1 = [('apple 5', 12), ('apple 3', 2), ('apple 6', 10),('apple 4', 15), ('apple 9', 11), ('apple 7', 14), ('apple 18', 10), ('apple 16', 10),('orange 5', 4), ('orange 4', 7)]
    
    def sort_key(x):
        word, num = x[0].split()
        return word, int(num), x[1] # Sort by word, than the number as an integer, than the final number
    
    l1.sort(key=sort_key)
    print(*l1, sep='\n')
    

    输出:

    ('apple 3', 2)
    ('apple 4', 15)
    ('apple 5', 12)
    ('apple 7', 14)
    ('apple 9', 11)
    ('apple 16', 10)
    ('apple 18', 10)
    ('orange 4', 7)
    ('orange 5', 4)
    

    【讨论】:

      【解决方案2】:

      您可以使用自己的key进行排序,并使用多个条件,语法为sorted(values, key = lambda x: (criteria_1, criteria_2))

      values = [('apple 5', 12), ('apple 3', 2), ('apple 6', 10), ('apple 4', 15),
                ('apple 9', 11), ('apple 7', 14), ('apple 18', 10), ('apple 16', 10),
                ('orange 5', 4), ('orange 4', 7)]
      
      for i in sorted(values, key=lambda x: (x[0].split(" ")[0], int(x[0].split(" ")[1]))):
          print(i)
      

      或者使用方法获取正确的代码

      def splitter(v: str):
          s = v.split(" ")
          return s[0], int(s[1])
      
      for i in sorted(values, key=lambda x: splitter(x[0])):
          print(i)
      

      【讨论】:

        猜你喜欢
        • 2019-05-26
        • 2020-02-18
        • 1970-01-01
        • 2016-01-23
        • 1970-01-01
        • 2011-03-07
        • 2016-10-28
        相关资源
        最近更新 更多