我正在寻找一个从第二个项目开始然后由第一个项目开始的元组列表排序。这不是Sort tuple by first then second then third的重复内容,因为该帖子大约是第一然后第二,而不是第二然后第一。
来自C#背景,我会发现很多类似OrderBy + ThenBy的东西。
我可以自己编写并寄出。 Python包含电池,我相信有更好的方法来实现这一目标。
mcve和单元测试:
def sort_tuples_by_second(inputs):
return sorted(inputs, key=lambda item: item[1])
class TestStringMethods(unittest.TestCase):
# both passed
def test_sort_tuples_by_second(self):
tuples = [(1, 1), (1, 2), (1, 0), (0, 9)]
actuals = sort_tuples_by_second(tuples)
self.assertEqual(actuals, [(1, 0), (1, 1), (1, 2), (0, 9)])
letters = [("a", "a"), ("b", "c"), ("c", "b"), ("a", "z")]
actuals = sort_tuples_by_second(letters)
self.assertEqual(actuals, [("a", "a"), ("c", "b"), ("b", "c"), ("a", "z")])
# both failed
def test_sort_tuples_by_second_then_by_first(self):
tuples = [(1, 1), (4, 1), (3, 1), (1, 9), (0, 9)]
actuals = sort_tuples_by_second(tuples)
self.assertEqual(actuals, [(1, 1), (3, 1), (4, 1), (0, 9), (1, 9)])
letters = [("b", "a"), ("a", "a")]
actuals = sort_tuples_by_second(letters)
self.assertEqual(actuals, [("a", "a"), ("b", "a")])
答案 0 :(得分:0)
您正在寻找一种内置方式,有两种!您可以通过查看python dev如何对其他数据结构进行排序来找到它们。例如,sort a list of dicts by x then by y上有一些提示。在这种情况下,它们按键排序:
list.sort(key=lambda item: (item['points'], item['time']))
或者在您使用元组的情况下:
sorted(inputs, key=lambda item: (item[1], item[0]))
Python的HowTo提供了另一种选择:
from operator import itemgetter
sorted(inputs, key=itemgetter(1, 0))