【问题标题】:Sort tuples list with last element [duplicate]使用最后一个元素对元组列表进行排序[重复]
【发布时间】:2018-01-24 14:04:42
【问题描述】:

需要用最后一个元素对给定的元组列表进行排序

def sort_last(tuples):
    sorted_list = []
    i = 0
    i2 = 1
    while True:
        if len(tuples) == 2:
            if tuples[i][-1] < tuples[i2][-1]:
                sorted_list.append(tuples[i])
                sorted_list.append(tuples[i2])
                break
            else:
                sorted_list.append(tuples[i2])
                sorted_list.append(tuples[i])
                break
        elif tuples[i][-1] < tuples[i2][-1]:
            i2 += 1
            print 1
        elif i == i2:
            i2 += 1
        elif i2 == len(tuples)-1:
            if tuples[i][-1] < tuples[i2][-1]:
                sorted_list.append(tuples[i])
                del tuples[i]
                i = 0
                i2 = 1
            else:
                sorted_list.append(tuples[i2])
                del tuples[i2]
                i = 0
                i2 = 1
        elif len(tuples) <= 1:
            return tuples
        else:
            i += 1
    return sorted_list

对于像([(1, 3), (3, 2), (2, 1)])([(2, 3), (1, 2), (3, 1)]) 这样的元组列表,它会正确返回:([(2, 1), (3, 2), (1, 3)])([(3, 1), (1, 2), (2, 3)]),但是对于 3+ 个元素元组或 4 个元组列表,它会写入 "list index out of range"

【问题讨论】:

  • 按最后一个元素排序是什么意思?
  • 为什么不直接使用sorted?这个问题我没有得到更多信息吗?

标签: python python-2.7


【解决方案1】:
def sort_last(tuples):
    return sorted(tuples, key=lambda i: i[-1])

>>> sort_last([(1, 3), (3, 2), (2, 1)])
[(2, 1), (3, 2), (1, 3)]
>>> sort_last([(2, 3), (1, 2), (3, 1)])
[(3, 1), (1, 2), (2, 3)]

【讨论】:

    【解决方案2】:
    a=([(1, 3), (3, 2), (2, 1)])
    def foo(elem):
        return elem[-1]
    a.sort(key=foo)
    print(a)
    

    【讨论】:

    • 请添加您的代码说明。无需描述就能理解的人也可以自己编写代码。
    猜你喜欢
    • 1970-01-01
    • 2012-03-13
    • 2012-03-11
    • 2016-03-17
    • 2021-11-22
    • 2017-03-21
    • 2013-01-27
    • 2020-08-02
    相关资源
    最近更新 更多