Replace element in list with element from another list - Python -
i have list named rule.start.
in list, elements equal element list called com.empty
. want element rule.start
replaced element comes after same element com.empty
. how this?
rule.start
looks this:
['f', 'l', 'g', 'l', 'f', 'r', 'f', 'r', 'f', 'l', 'g', 'l', 'f', 'l', 'f', 'l', 'g', 'l', 'f', 'l',........]
com.empty
looks this:
['f', ['fd'], 'g', ['fd'], 'l', ['lt', '60'], 'r', ['rt', '60']]
i have tried this:
wut = 0 elem in rule.start: v = 1 mel in com.empty[::2]: if elem == mel: rule.start[wut] = com.empty[v] print elem print mel wut +=1 v += 2
but replaces element of rule.start ['fd']
in end, want evaluate elements commands, looks this: fd(var, scale)
and this: rt(var, 60) # 60 list.
first, much easier write, , lot more efficient, if had dictionary, mapping keys values, instead of list of alternating keys , values. can one-liner:
mapping = dict(zip(com.empty[::2], com.empty[1::2]))
but if don't understand how works, can this, should able understand (based on code).
mapping = {} key = none mel in com.empty: if key none: key = mel else: mapping[key] = mel key = none
or, better, if possible, alter code build dict instead of list of alternating values in first place.
now, 1 time have this, loop becomes dead simple, , hard wrong:
for wut, elem in enumerate(rule.start): rule.start[wut] = mapping.get(elem, elem)
i'm using enumerate
don't have maintain track of wut
manually, , i'm using dict.get
method instead of looping on keys , values, tricky part got lost in.
or, more simply:
rule.start = [mapping.get(elem, elem) elem in rule.start]
but, if want know what's wrong attempt:
you start off v = 1
. each mel
, increment v
2 if elem == mel
. otherwise, stays @ 1. so, first time elem == mel
, you're going have v = 1
, you're going assign com.empty[1]
rule.start[wut]
. if move v + 2
outside loop, prepare problem.
you have similar problem wut += 1
beingness in wrong place. should updated every elem
; instead, it's updated every elem
, mel
match, 0 times or (theoretically) 3 times.
getting stuff right big source of errors, why enumerate
exists.
python list
No comments:
Post a Comment