Python permutation as list comprehension -
i've got list of strings , permutation. i'm trying apply permutation list, i'm trying keep code clean , concise. @ moment have working solution, , looks this:
mylist = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'] permutation = [5,2,6,3,7,9,1,4,8] mynewlist = ['']*9 in range(9): mynewlist[permutation[i]-1] = mylist[i] print mynewlist
what don't have initialize list empty list first, , loop through in odd manner. wondering if come cleaner way write this, perhaps using list comprehension? or applying map?
for reference purposes - result of above is:
['g', 'b', 'd', 'h', 'a', 'c', 'e', 'i', 'f']
your algorithm, cleaner:
mynewlist = mylist[:] pos, elem in zip(permutation, mylist): mynewlist[pos - 1] = elem
Comments
Post a Comment