0

I've written the code below:

items = [[1,91],[1,92],[2,93],[2,97],[1,60],[2,77],[1,65],[1,87],[1,100],[2,100],[2,76]]

sorted_items = sorted(items, key=lambda x: x[0])

for i in sorted_items:
    if i[0] == (i+1)[0]: 

The above code gives me an error- particularly for the last line of code. My question is, how do I reference the first index of lists within lists? I hope the question is clear from the last line of my code.

i.e. i[0] is okay, but Python doesn't allow (i+1)[0]; how else can I write this?

Thanks.

Just a follow on from my question above:

for i in range(len(sorted_items)-1):
    if sorted_items[i][0] == sorted_items[i+1][0]:
        final_sorted_items = sorted(sorted_items, key=lambda x:x[1], reverse=True)

print(final_sorted_items)

So I have added the line but it doesn't do the job that I am after. I basically want to sort the smaller lists in descending order if the first index is the same. Any idea how to amend my code to do this? Cheers

2 Answers2

1

That i you're trying to use like i+1 is a list already. If you want to achieve this, you should use range.

    items = [[1,91],[1,92],[2,93],[2,97],[1,60],[2,77],[1,65],[1,87],[1,100],[2,100],[2,76]]

    sorted_items = sorted(items, key=lambda x: x[0])

    for i in range(0, len(sorted_items)-1):
        if sorted_items[i][0] == sorted_items[i+1][0]:
            #do your stuff
Eagleclaw
  • 369
  • 1
  • 13
  • Just added the len(sorted_items)-1 to your code, otherwise it will crash on the last index cause you lookup for i+1 (index out of range). – Synthase Apr 01 '21 at 07:15
  • I missed that part, thanks for correcting it. – Eagleclaw Apr 01 '21 at 07:17
  • Also, the last line of code, is it meant to read sorted_items[i+1][0] ; or is the (i+1) meant to be in circular brackets? –  Apr 01 '21 at 10:27
  • Oh, you're right, it should be [] not (), my bad again. Sorry for rush answer. I edited and fixed it. – Eagleclaw Apr 01 '21 at 10:35
0
items = [[1,91],[1,92],[2,93],[2,97],[1,60],[2,77],[1,65],[1,87],[1,100],[2,100],[2,76]]

sorted_items = sorted(items, key=lambda x: x[0])

for i in range(len(sorted_items)-1):
    if sorted_items[i][0] == sorted_items[i+1][0]:
        pass

I don't know what is the purpose of your code, but if you want to get all list elements such as value at index 0 of element is equal to value at index 0 of next element in list then you could:

l = [ sorted_items[i] for i in range(len(sorted_items)-1) if sorted_items[i][0] == sorted_items[i+1][0] ]
Synthase
  • 5,849
  • 2
  • 12
  • 34
  • The purpose is to first identify all of the (smaller) lists with the same 0th index; which your code above does just fine. But then for those with the same 0th index, I want to sort by the 1st index (i.e. the higher scores) in descending order. So for example if we had [[1,91] , [1,92] , [1,93 ]] ->. [[1,93] , [1,92] , [1,91]] –  Apr 01 '21 at 20:39