-Python- Ordering lists based on a format -


i'm new programming in general, looking expand skills here. i'm trying write script grab list of strings object, order them based on template of design. items not in template added end.

here's how i'm doing now, suggest better/more efficient way?

    originallist = ['b', 'a', 'c', 'z', 'd']     listtemplate = ['a', 'b', 'c', 'd']     listfinal = []      thing in listtemplate:         if thing in originallist:             listfinal.append(thing)             originallist.pop(originallist.index(thing))      thing in originallist:             listfinal.append(thing)             originallist.pop(originallist.index(thing)) 

try this:

originallist = ['b', 'a', 'c', 'z', 'd'] listtemplate = ['a', 'b', 'c', 'd']  order = { element:index index, element in enumerate(listtemplate) } sorted(originallist, key=lambda element: order.get(element, float('+inf')))  => ['a', 'b', 'c', 'd', 'z'] 

this how works:

  • first, build dictionary indicating, each element in listtemplate, relative order respect others. example a 0, b 1 , on
  • then sort originallist. if 1 of elements present in order dictionary, use relative position ordering. if it's not present, return positive infinite value - guarantee elements not in listtemplate end @ end, no further ordering among them.

the solution in question, although correct, not pythonic. in particular, whenever have build new list, try use list comprehension instead of explicit looping/appending. , it's not practice "destroy" input list (using pop() in case).


Comments

Popular posts from this blog

c# - Send Image in Json : 400 Bad request -

javascript - addthis share facebook and google+ url -

ios - Show keyboard with UITextField in the input accessory view -