'Is there a way to make something like this shortened and more improved?

max_verts = []
for image in images:
    newlist = []
    for accessor in accessors:
        if accessor.bufferView <= image.bufferView and accessor.max:
            newlist.append(accessor.count)
    max_verts.append(sum(newlist))
print(list(itertools.accumulate(max_verts)))

I'm working on optimizing and improving my code, are there any ways to shorten this? There's a lot of for loops and temporary lists, I would appreciate any help or advice.



Solution 1:[1]

Not sure if this is what you're looking for but the inner loop that appends to new_list ultimately ends up getting summed up, so you can use a generator expression instead

# loop through images until the penultimate image
max_verts = [sum(accessor.count for accessor in accessors if accessor.bufferView <= image.bufferView and accessor.max) for image in images[:-1]]
# do a separate construction for the last image
max_verts.append(sum(accessor.count for accessor in accessors if accessor.max))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1