简体   繁体   English

按 python3.x 升序对给定的二维数组进行排序

[英]Sort given 2d array in order of ascending by python3.x

I am a python beginner, please help me with this python case.我是 python 初学者,请帮我解决这个 python 案例。

Sort given 2d array in order of ascending.Flatten the 2D array, and sort it such that first sort order is the first number, second sort order is the second number'''# Example:input_arr = [ ['55-29', '55-32', '62-3', '84-38'], ['36-84', '23-53', '22-58', '48-15'], ['72-80', '48-6', '11-86', '73-23'], ['93-51', '55-11', '93-49', '72-10'], ['93-66', '71-32', '16-75', '55-9'],] ouput_arr = ['11-86', '16-75', '22-58', '23-53', '36-84', '48-6', '48-15', '55-9', '55-11', '55-29', '55-32', '62-3', '71-32', '72-10', '72-80', '73-23', '84-38', '93-49', '93-51', '93-66'] def sort_2d_array(input_arr=input_arr) -> list: #TODO pass按升序对给定的二维数组进行排序。将二维数组展平,并对其进行排序,使得第一个排序顺序是第一个数字,第二个排序顺序是第二个数字'''# 示例:input_arr = [ ['55-29', '55-32', '62-3', '84-38'], ['36-84', '23-53', '22-58', '48-15'], ['72-80' ', '48-6', '11-86', '73-23'], ['93-51', '55-11', '93-49', '72-10'], ['93 -66', '71-32', '16-75', '55-9'],] ouput_arr = ['11-86', '16-75', '22-58', '23-53' , '36-84', '48-6', '48-15', '55-9', '55-11', '55-29', '55-32', '62-3', ' 71-32'、'72-10'、'72-80'、'73-23'、'84-38'、'93-49'、'93-51'、'93-66'] def sort_2d_array( input_arr=input_arr) -> 列表:#TODO 传递

Try this you need to flatten your list into single list like this试试这个,你需要将你的列表展平成这样的单个列表

tmp = [t for x in input_arr for t in x]

then do the sorting based on first element before the - , like this然后根据-之前的第一个元素进行排序,就像这样

print(list(sorted(tmp,key=lambda x: int(x.split('-')[0]))))

this will give you your desired output.这将为您提供所需的 output。

['11-86', '16-75', '22-58', '23-53', '36-84', '48-15', '48-6', '55-29', '55-32', '55-11', '55-9', '62-3', '71-32', '72-80', '72-10', '73-23', '84-38', '93-51', '93-49', '93-66']

for second condition you can try对于第二种情况,您可以尝试

print(list(sorted(tmp,key=lambda x: (int(x.split('-')[0]) , int(x.split('-')[1])))))

this will give you这会给你

['11-86', '16-75', '22-58', '23-53', '36-84', '48-6', '48-15', '55-9', '55-11', '55-29', '55-32', '62-3', '71-32', '72-10', '72-80', '73-23', '84-38', '93-49', '93-51', '93-66']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM