简体   繁体   中英

Uniquely sorting a list of lists in Python

I have a list of lists -

super_list = [seconds, self.flowdata, key]

where seconds is a ten digit number, self. flowdata is a list of 160 integers and key is an identifying string. Printing super_list would yield many iterations of the following structure, all with different values,

example:

"[[1509321600], 
  ['1', '-1', '4', '7', '7', '1', '-8', '-14', '-24', '-29', '-25', '-24', '-9', '-4', '0', '0', '-5', '-10', '-6', '-5', '7', '-4', '-4', '-11', '5', '3', '9', '5', '3', '3', '6', '-6', '-8', '-6', '-6', '25', '23', '30', '22', '13', '-7', '0', '-1', '-18', '-24', '-28', '-24', '-24', '-18', '-14', '-14', '-12', '-13', '-11', '-15', '-16', '-8', '-3', '-4', '-2', '11', '29', '38', '40', '41', '29', '34', '25', '20', '15', '31', '22', '16', '2', '8', '21', '39', '43', '45', '38', '39', '37', '38', '41', '43', '42', '38', '34', '34', '25', '25', '29', '18', '23', '27', '26', '18', '15', '15', '11', '17', '10', '11', '4', '-3', '-12', '-17', '-14', '6', '5', '13', '4', '-21', '-22', '-16', '-12', '-6', '4', '16', '9', '17', '16', '16', '16', '15', '12', '12', '7', '-2', '-12', '-13', '-5', '-7', '-8', '-12', '-15', '-14', '-11', '-8', '-1', '-1', '-3', '-12', '-7', '-6', '-7', '5', '4', '2', '3', '1', '0', '-12', '-12', '-13', '-17', '-18', '-18', '-15', '-13', '-13', '-16', '-17', '-18', '-18', '-19', '-16', '-13'], 
  '1441-4731-1-10/30/2017']

Each set (or row if you like, as seen above) of seconds, flowdata and key are related.

I want to sort super_list so that seconds is ordered from smallest to largest, but also with its correlating flowdata and key in the same numerical 'row' in super_list.

ie say the above example was to be the first in the sorted list(1509321600 was the smallest number of seconds in the seconds list), the above flowdata would also be the first in flowdata and the above key "1441-4731-1-10/30/2017" would be the first key.

Help?

Assuming your list looks like: [[seconds1, flowdata1, key1], [seconds2, flowdata2, key2], ...] :

Just use super_list.sort() .

This will sort by the fields in lexicographic (left-to-right) order. Since seconds is the leftmost field, all entries will be sorted by it.

You can also sort by a specific field by using the key parameter to sort , eg:

super_list.sort(key=lambda row: row[0]) #sort by seconds field

You could zip the lists into a tuple and then sort the list of tuples, then unpack the tuples with a list comprehension, like so:

super_list = [seconds, flowdata, key for zipped_tuple in sorted(zip(super_list[0], super_list[1], super_list[2]))]

where seconds, flowdata, key, and zipped_tuple are arbitrary names with no scope beyond the list comprehension.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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