python - Unable to insert values into a list at the correct index -
i receive list of numbers , want sort them. input looks this:
i:1,3,5,8 n:2 t:4,7 a:6 v:9 and comes in form of txt file.
the code looks this:
flat_list = [item sublist in decks item in sublist] p = [] x in range(len(flat_list)): nr = flat_list[x][0] o = nr -1 p.insert((o),(flat_list[x][1])) print(p) which gives output:
[(1, 'i'), (2, 'n'), (3, 'i'), (4, 't'), (5, 'i'), (6, 'a'), (8, 'i'), (7, 't'), (9, 'v')] which want, except 7 , 8. do wrong ?
you declare empty list:
p = [] but call list.insert on it. this, unfortunately, leads unintended side effects. observe:
in [209]: p.insert(999, 0) in [210]: p out[210]: [0] which inserted @ 0th position, despite fact wanted in (999 + 1)th place. sort of thing reason see items in wrong place, never inserted begin with.
the fix multiply [none] list. also, should able simplify insertion logic drastically, if iterate on elements rather indices.
p = [none] * len(flat_list) i, y in flat_list: p[i - 1] = y
Comments
Post a Comment