Python程序打印通过合并数组中的所有元素形成的排序数字
给定一个数组 arr[],任务是将数组中的所有元素按顺序组合起来,并按升序对这个数字的数字进行排序。
注意:忽略前导零。
例子:
Input: arr =[7, 845, 69, 60]
Output: 4566789
Explanation: The number formed by combining all the elements is “78456960” after sorting the digits we get 4566789
Input: arr =[8, 5603, 109, 53209]
Output: 1233556899
Explanation: The number formed by combining all the elements is “8560310953209” after sorting the digits we get “1233556899”
方法:
- 使用 map()函数将列表的每个元素转换为字符串。
- 使用 join()函数加入列表。
- 使用 join() 和 sorted() 对字符串进行排序
- 使用类型转换将字符串转换为整数
- 返回结果
下面是上述方法的实现:
Python3
# python program to print sorted number by merging
# all the elements in array function to print
# sorted number
def getSortedNumber(number):
# sorting the string
number = ''.join(sorted(number))
# converting string to integer
number = int(number)
# returning the result
print(number)
# function to merge elements in array
def mergeArray(lis):
# convert the elements of list to string
lis = list(map(str, lis))
# converting list to string
string = ''.join(lis)
# passing this string to sortednumber function
getSortedNumber(string)
# Driver code
lis = [7, 845, 69, 60]
# passing list to merge array function to merge
# the elements
mergeArray(lis)
输出:
4566789