-1

I receive a list of numbers and I want to sort them. the input looks like this:

i:1,3,5,8
n:2
t:4,7
a:6
v:9

and comes in form of a txt file.

The code looks like this:

flat_list = [item for sublist in decks for item in sublist]
p = [] 

for 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 this output:

[(1, 'i'), (2, 'n'), (3, 'i'), (4, 't'), (5, 'i'), (6, 'a'), (8, 'i'), (7, 
 't'), (9, 'v')]

which is almost what I want, it except for 7 and 8. so what do I do wrong ?

cs95
  • 379,657
  • 97
  • 704
  • 746
  • @timgeb The question is clear no? They want to know why their code doesn't result in a sorted output. However, they should show the original input, show us `decks` – Chris_Rands Sep 11 '17 at 09:52
  • I don't think you understand what `p = []*(len(flat_list)-1) ` is doing. – cs95 Sep 11 '17 at 09:53
  • @Chris_Rands Kind of. I employed some snark because the question OP seems to be asking is unanswerable as he did not provide any context about his data structures. – timgeb Sep 11 '17 at 09:55
  • @timgeb Well they only joined SO today, and they've edited it now, be nice don't forget :) – Chris_Rands Sep 11 '17 at 09:58

2 Answers2

1

You declare an empty list:

p = [] 

But you call list.insert on it. This, unfortunately, leads to some unintended side effects. Observe:

In [209]: p.insert(999, 0)

In [210]: p
Out[210]: [0]

Which is inserted at the 0th position, despite the fact that you wanted it in the (999 + 1)th place. This sort of thing is the reason you see items in the wrong place, they were never inserted properly to begin with.


The fix would be to multiply a [None] list. Also, you should be able to simplify your insertion logic drastically, if you iterate over the elements rather than their indices.

p = [None] * len(flat_list) 

for i, y in flat_list: 
    p[i - 1] = y
cs95
  • 379,657
  • 97
  • 704
  • 746
0

You should really work on phrasing your questions.

But I believe this might be the answer you're looking for.

from operator import itemgetter
flat_list = [(1,a),(6,b),(3,d),(7,c),(9,a),(4,b)]
sorted(flat_list, key=itemgetter(0))

I found this by googling a little, maybe you should try the same.