itertools - sorting multiple lists in python based on sorting of a single list -
i python newbie here, , have been struck on rather simple problem - , looking efficient way solve this. so, have 5 lists follows:
a,b,c,d,score
where above lists have same size (500 in case). a,b,c,d
string lists , score
int
list.
what sort a,b,c,d
based on ascending or descending sorting of score
. so, first want sort score
based on descending pattern, , sort corresponding elements in a,b,c,d
based on sorted score list (in same order).
i thinking of enumerate
achieve this, wondering if itertools
used here make faster , more efficient.
any guidance on how can achieved appreciated && sorry if 101 question.
sorted_lists = sorted(izip(a, b, c, d, score), reverse=true, key=lambda x: x[4]) a, b, c, d, score = [[x[i] x in sorted_lists] in range(5)]
in first step, zip
lists together. takes first element every list , puts them tuple, appends tuple new list, same second element in every list, , on. sort list of tuples fifth element (this anonymous function passed key
argument). set reverse=true
list descending.
in second step, split lists out using nested list comprehensions , tuple unpacking. make new list of lists, each inner list first elements of each tuple in sorted_lists
. in 1 line below, think splitting 2 pieces may bit clearer:
a, b, c, d, score = izip(*sorted(izip(a, b, c, d, score), reverse=true, key=lambda x: x[4]))
here generic function returns list of tuples, tuples sorted lists:
def sort_lists_by(lists, key_list=0, desc=false): return izip(*sorted(izip(*lists), reverse=desc, key=lambda x: x[key_list]))
Comments
Post a Comment