
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Program to sort all elements in a given list and merge them into a string in Python
Suppose we are given a list of positive integers. We have to sort the list in descending order and then have to join all the elements in it to form a string. We return the joined string.
So, if the input is like input = [415, 78, 954, 123, 5], then the output will be 954785415123
To solve this, we will follow these steps −
- Define a function cmp() . This will take l, r
- if integer value of (string representation of (l) + string representation of (r)) > integer value of (string representation of (r) + string representation of (l)), then
- return 1
- otherwise,
- return -1
- if integer value of (string representation of (l) + string representation of (r)) > integer value of (string representation of (r) + string representation of (l)), then
- sort the list input according to the function compare
- join all the elements in input into a string and return it.
Example
Let us see the following implementation to get better understanding −
from functools import cmp_to_key def cmp(l, r): if int(str(l) + str(r)) > int(str(r) + str(l)): return 1 else: return -1 def solve(input): input.sort(key=cmp_to_key(cmp), reverse=True) return "".join(map(str, input)) print(solve([415, 78, 954, 123, 5]))
Input
[415, 78, 954, 123, 5]
Output
954785415123
- Related Articles
- Program to sort a given linked list into ascending order in python
- Program to merge intervals and sort them in ascending order in Python
- Python program to sort and reverse a given list
- Python Program to check whether all elements in a string list are numeric
- Write a program in Python to sort all the elements in a given series in descending order
- Sort a list according to the Length of the Elements in Python program
- Program to check a string can be broken into given list of words or not in python
- Python program to print elements which are multiples of elements given in a list
- Write a Python program to shuffle all the elements in a given series
- Write a program in Python to round all the elements in a given series
- Python Program To Convert An Array List Into A String And Viceversa
- Python Program to Put Even and Odd elements in a List into Two Different Lists
- Python Program for Merge Sort
- Program to find list of all possible combinations of letters of a given string s in Python
- Python - Ways to merge strings into list

Advertisements