Hello world!
My goal is pretty simple: I want to split my HB rooms in two lists, one containing the smallest room (by floor area) and the other list containing the rest. I already managed to do it with a GhPython script plus some native list components, as you can see bellow. However, I was wondering how to execute the whole task only by scripting. I tried to sort the x.floor_area but I get a Runtime error saying that ‘float’ object has no attribut sort, although I though the results were arranged in a list.
Model sorting.gh (27.9 KB)
Hi!
if you want to do it in pure ghpy:
For copy/paste:
# make a container for what we want to interogate
floor_area_list = []
# go through each list item and fill container with the desired
for room in _rooms:
floor_area_list.append(room.floor_area)
# sort ascending:
a = sorted(floor_area_list)
# get smallest
# list items have an index from 0 -> end of list index
b = a[0]
# sort descending
c = sorted(floor_area_list, reverse = True)
print(floor_area_list)
print(a)
print(b)
print(c)
There is likely a way to do this with list comprehension as well.
Also Grasshopper uses python 2.7 (ironpython) which is a good bit different here and there from python 3.xx so add to any python related google python 2.7 and it should return better results for ghpy stuff.
This is a sorting with py 2.7 reference for sorting lists, I am not explicitly clear on if there is a way to .sort in 2.7 but this at least: does work for sure
best
@TrevorFedyna
3 Likes
That’s pretty much what I was looking for, thank you for the help!
But just to complement your answer, it should be noted that we must choose “List Access” for _rooms. Besides, since the initial goal was to get the rooms sorted by their floor_area, I decided to sort them by doing [x for _, x in sorted(zip(floor_area_list, _rooms))].
Here is the edited code:
import rhinoscriptsyntax as rs
# make a container for what we want to interogate
floor_area_list = []
# go through each list item and fill container with the desired
for room in _rooms:
floor_area_list.append(room.floor_area)
# sort ascending:
a = sorted(floor_area_list)
# get smallest
# list items have an index from 0 -> end of list index
b = a[0]
# sort descending
c = sorted(floor_area_list, reverse = True)
# sort rooms according to a (floor_area_list)
sorted_rooms = [x for _, x in sorted(zip(floor_area_list, _rooms))]
Cheers,
Gustavo
2 Likes
If I understand the original question correctly you are not looking for the area itself. You just want them sorted based on the area. In that case, I would use the key
argument to make it easier. This single line should give you what you need:
a = sorted(x, key=lambda room: room.floor_area)
x
should be set to List Access.
4 Likes
What an elegant solution. Thank you a lot!
1 Like