0

Given a list_of_list from a SQL table, I'd like to analyze sets of adjacent rows dividing list_of_list for equal elements of column 2, then for equal element of column 1. For example, given

list_of_list = [[1,1,3,2],
[1,3,3,2],
[1,3,6,2],
[1,3,6,2],
[1,5,5,2],
[1,3,5,2]]

I'd like to get to following output

[1,1,3,2]

[1,3,3,2]

[1,3,6,2]
[1,3,6,2]

[1,5,5,2]

[1,3,5,2]

What's wrong in the following code?

for key1, items1 in groupby(list_of_list, itemgetter(2)):
    for key2, items2 in groupby(items1, itemgetter(1)):
        for i in items2:
            print(i)
            print

it returns the following output

[1,1,3,2]

[1,3,3,2]

[1,3,6,2]

[1,3,6,2]

[1,5,5,2]

[1,3,5,2]
7
  • can you give us a sample list_of_list and expected output? Like print(i) and tell us what it's supposed to print. Commented Mar 28, 2016 at 15:11
  • ok, I added an example Commented Mar 28, 2016 at 15:20
  • Your code already does that though, after unindenting last print one level Commented Mar 28, 2016 at 15:25
  • I added also what my code returns Commented Mar 28, 2016 at 15:36
  • Yes, if you unindent the last print, your code will start printing expected output Commented Mar 28, 2016 at 15:38

1 Answer 1

1

As mentioned in the comments, your code works fine if you unindent the last print statement:

for key1, items1 in groupby(list_of_list, itemgetter(2)):
    for key2, items2 in groupby(items1, itemgetter(1)):
        for i in items2:
            print(i)
        print

To get the first element of items2 you can use next like so:

first_of_items2 = next(items2, 'items2 was empty')
Sign up to request clarification or add additional context in comments.

3 Comments

It looks like with "for key, items in groupby(list_of_list, itemgetter(2,1))" I obtain the same effect. Can you confirm that it's a fair way to use it?
Looks alright, you can check the docs if anything. I'll take a look too when I get home tonight. It seems as if it's grouping by one and then the other though, so it should be fine.
Just verified - it generates a break or new group every time the value of the key function changes, so all you need to do is use combined key - as long as your items are sorted by that key you're fine. For more info, see here. Good luck!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.