Working with a list of lists ( Rhino Python)

Hey, I’ve got a list in rhino python which contains many lists of points. I want to select the two largest lists of points.
It sounds simple enough, but I am having a fair bit of trouble. I can get the lengths of the lists inside the list. So i have three of them ( lets say 80, 60 and 90) but I cant select based on this length.

Any help?

Thanks btw. I realise this is a noob issue.

You could sort your list of lists using a key that returns the length of the list with reverse set to true so the largest is first.

Below shows how to use sort with a key that I call getKey. If you do not include it, the list will not be sorted by length by default.

def getKey(item): return len(item)
a = [[1,2,4],[4,5,6,7,8],[1,2,3,4,5,6,7,8,9]]
a.sort(key = getKey, reverse = True)
print a
[[1, 2, 3, 4, 5, 6, 7, 8, 9], [4, 5, 6, 7, 8], [1, 2, 4]]

Here is what happens if you leave out key = getKey:

a = [[1,2,4],[4,5,6,7,8],[1,2,3,4,5,6,7,8,9]]
a.sort()
print a
[[1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 2, 4], [4, 5, 6, 7, 8]]

With the selection of the 2 largest lists included, the code becomes:

def getKey(item): return len(item)
a = [[1,2,4],[4,5,6,7,8],[1,2,3,4,5,6,7,8,9]]
a.sort(key = getKey, reverse = True)
b = a[:2]
print b
[[1, 2, 3, 4, 5, 6, 7, 8, 9], [4, 5, 6, 7, 8]]

Regards,
Terry.

2 Likes

(corrected sort key)
Hi you can use my_list.sort(key=len) to sort your list ‘in place’ and then big_two = my_list[-2:] to get the 2 largest. Sort works by default with the len() of the object so no need to specify the sort key.
To get the items one by one use pop()
-Graham

2 Likes

ahh yes don’t know what I was doing wrong with the sort method sort works by default by alphabetical order of the elements in the list, starting with item [0].
so you can use mylist.sort(key=len) to sort by length. Thanks for the correction @Terry_Chappell

1 Like