按第二个元素对元组列表进行排序,但如果多个元组的第二个元素匹配,则使用第一个元素进行排序

alt*_*r00 1 c++ python sorting tuples list

给定一个元组列表,其中第一个和第二个元素是整数。使用第二个元素对它们进行排序,但如果第二个元素匹配,则使用第一个元素对它们进行排序。基本上,我试图将c++ pair<int, int>类型比较转换为 python 代码。这是c++版本。

bool cmp(const pair<int,int>& a, const pair<int,int>& b)
{
    if(a.second != b.second) return a.second < b.second;
    return a.first < b.first;
}

int main() {
   //some code here

   sort(v.begin(), v.end(), cmp);

   //some code here

   return 0;
}
Run Code Online (Sandbox Code Playgroud)

这段代码产生,

input: [(2, 5), (3, 6), (1, 5), (8, 10), (6, 9)]

output: [(1, 5), (2, 5), (3, 6), (6, 9), (8, 10)]

我尝试将该代码转换为python

sil = [(2, 5), (3, 6), (1, 5), (8, 10), (6, 9)]

sil.sort(key = lambda y : y[1])
Run Code Online (Sandbox Code Playgroud)

但遗憾的是这只会产生output: [(2, 5), (1, 5), (3, 6), (6, 9), (8, 10)]. 显然,(1, 5) 应该出现在 (2, 5) 之前,但它没有发生。

我的问题是如何实现这个,python所以输出应该是[(1, 5), (2, 5), (3, 6), (6, 9), (8, 10)]

Mor*_*rtz 5

key您可以在-中指定这两个元素

inp = [(2, 5), (3, 6), (1, 5), (8, 10), (6, 9)]
sorted(inp, key=lambda x: (x[1], x[0]))
Run Code Online (Sandbox Code Playgroud)

输出

[(1, 5), (2, 5), (3, 6), (6, 9), (8, 10)]
Run Code Online (Sandbox Code Playgroud)

  • @altair00 是的。在Python中,使用标准的字典比较来比较元组:比较第一个元素,如果相等,则比较第二个元素,等等。这里`lambda x: (x[1], x[0])`负责交换第一个和第二个元素。 (2认同)