View Full Version : [python] modify a list
10-11-2011, 11:45 AM
Hi there ,
i would like to reorder a list by filtering it , but dont find how.
i got a list : [curve1, curve2, curve3, subCurve1, subCurve2] and would like to get : [curve1, subCurve1, curve2, subcurve2, curve3] .
is it something that is possible?
10-11-2011, 12:37 PM
Not very elegant way, but should work.
newList = 
for i in curveList:
subname = i.replace("curve", "subCurve")
if subname in curveList:
10-11-2011, 01:55 PM
Thanks you !
why did you say" it s not a elegant way" to do that?
10-11-2011, 02:13 PM
your question is not quite explicit enough.
do you simply want to "group" a curve# with a corresponding subCurve#..? or do you mean you want to SORT the list based on the number in the name?
what happens if the names are NOT curve#and subCurve#..?
Haggi's solution only works for the former, and doesn't actually sort them into order (which may not be an issue, you didn't specify). That's why he says it's not very elegant, it only works for a very specific situation.
For the latter method, if you wanted to sort your list based on an arbitrary index somewhere in it's name, python sort is customizable so you can sort based on any part of an item:
li = ['curve3', 'curve1', 'curve2', 'subCurve1', 'subCurve4', 'curve6']
li.sort(key=lambda x: re.search('[0-9]+',x).group())
print lithe sort key is a little complicated due to the lambda and the regular expressions, but show's what you can do with very little.
10-11-2011, 02:30 PM
yep , i realised it was not explicit enough.
The idea is i create some main Controllers [ctrlCrv1,ctrlCrv2,ctrlCrv3.....]
Then , i have some secondary controllers whixh can be : [subCtrl1, subCtrl2,subCtrl3 ....]
or : [subCtrl1_1, subCtrl1_2, subCtrl2_1, subCtrl2_2....]
What i want to do is to sort the list of all the controllers in this way :
[ctrlCrv1, subCtrl1_1, subCtrl1_2, ctrlCrv2, subCtrl2_1, subCtrl2_2..... ]
Your solution is exactly what i need .
i just learn something very useful.
Thanks to both of you
10-11-2011, 10:07 PM
Thats what I call more elegant :)
I'm not very good with lambdas, but I like the compact form.
10-11-2011, 10:07 PM
This thread has been automatically closed as it remained inactive for 12 months. If you wish to continue the discussion, please create a new thread in the appropriate forum.