鍍金池/ 問(wèn)答/Python  C++/ python中有沒(méi)有類似c++這種快速的字符串排序函數(shù)?

python中有沒(méi)有類似c++這種快速的字符串排序函數(shù)?

題目描述:

設(shè)有 n 個(gè)正整數(shù),將他們連接成一排,組成一個(gè)最大的多位整數(shù)。
如: n = 3 時(shí),3 個(gè)整數(shù) 13, 312, 343 連成的最大整數(shù)為 34331213。
如: n = 4 時(shí), 4 個(gè)整數(shù) 7, 13, 4, 246 連接成的最大整數(shù)為 7424613。

輸入描述:

有多組測(cè)試樣例,每組測(cè)試樣例包含兩行

  1. 第一行為一個(gè)整數(shù) N (N <= 100)
  2. 第二行包含 N 個(gè)數(shù)(每個(gè)數(shù)不超過(guò) 1000,空格分開(kāi))。

輸出描述:

每組數(shù)據(jù)輸出一個(gè)表示最大的整數(shù)。

示例 1:

# 輸入
2
12 123
4
7 13 4 246
# 輸出
12312
7424613

konnn 給出的 c++ 答案:

#include <string>
#include <algorithm>
#include <vector>
#include <iostream>

using namespace std;
    
int main() {
    int n; 
    cin >> n;
    vector<string> sArray;
    for (int i=0;i<n;i++) {
        string temp;
        cin >> temp;
        sArray.push_back(temp);
    }
    sort(sArray.begin(), sArray.end(), [](string s1, string s2){
        return (s1+s2) > (s2+s1);
    });
    for (auto s:sArray) {
        cout << s;
    }
    return 0;
}

python 中有沒(méi)有類似這樣的語(yǔ)句?

sort(sArray.begin(), sArray.end(), [](string s1, string s2){
    return (s1+s2) > (s2+s1);
});
回答
編輯回答
伴謊

python2:

>>> s = ['7', '13', '4', '246']
>>> print(''.join(sorted(s, cmp=lambda x,y: int(y+x)-int(x+y))))
7424613

python3:

from functools import cmp_to_key
>>> s = ['12', '123']
>>> print(''.join(sorted(s, key=cmp_to_key(lambda x,y: int(y+x)-int(x+y)))))
12312
2017年8月12日 14:32
編輯回答
憶往昔
#!/usr/bin/python

aList = [123, 'xyz', 'zara', 'abc', 'xyz'];
aList.sort();
print "List : ", aList
2018年1月17日 12:35