Just starting to work on python and having difficulties sorting string list by multiple/varying number of matches. Basically, given a list of strings, I need to split each string by a given regex (user provided) then sort by given list of keys (locations). The key can either be single integer or a list in the order in which they should be sorted. For example:
regex = r'.(FF|TT|SS)_([-.\d]+v)_([-.\d]+c)_(FF|TT|SS).'
key = [2,1,3]
Would sort the list of strings by location2, location1, location3.
I have the following that works for a fixed number of locations/keys, but can't figure out how to get it to work of varying number of 'keys':
import re
strlist = ["synopsys_SS_2v_-40c_SS.lib","synopsys_SS_1v_-40c_SS.lib","synopsys_SS_2v_-40c_TT.lib","synopsys_FF_3v_-40c_FF.lib", "synopsys_TT_4v_125c_TT.lib", "synopsys_TT_1v_-40c_TT.lib"]
regex = r'.*(FF|TT|SS)_([-\.\d]+v)_([-\.\d]+c)_(FF|TT|SS).*'
key = [2,1,3]
sfids_single = sorted(strlist, key=lambda name: (
re.findall(regex,name)[0][key[0]],
re.findall(regex,name)[0][key[1]],
re.findall(regex,name)[0][key[2]]))
Tried the following but it does not seem to work:
fids_single = sorted(strlist, key=lambda name: (re.findall(regex,name)[0][i] for i in key))
Also tried (w/o success):
for i in key:
strlist.sort(key=lambda name: re.findall(regex,name)[0][key[i]])
Expected result:
['synopsys_SS_1v_-40c_SS.lib', 'synopsys_TT_1v_-40c_TT.lib', 'synopsys_SS_2v_-40c_SS.lib', 'synopsys_SS_2v_-40c_TT.lib', 'synopsys_FF_3v_-40c_FF.lib', 'synopsys_TT_4v_125c_TT.lib']
Am I on the wrong track completely? Any guidance is greatly appreciated.