T8dgPWQ5
T8dgPWQ5

Reputation: 9

Is there a way to shorten nested for loops?

I have this:

for mesh in meshes:
    for primitive in mesh.primitives:
        print(accessors[primitive.attributes.POSITION])

Are there any ways to shorten this? I'm trying to make my code more compact and reduce the number of lines. I'm just wondering if there's a way to make this shorter.

Upvotes: 0

Views: 130

Answers (3)

Mehdi
Mehdi

Reputation: 4318

If this loop gets repeated in your code, you can make a generator for it:

def premitive_gen(meshes):
    for mesh in meshes:
        for primitive in mesh.primitives:
            yield primitive

then you can use it like this:

for primitive in premitive_gen(meshes):
     print(accessors[primitive.attributes.POSITION])

Upvotes: 0

Mechanic Pig
Mechanic Pig

Reputation: 7751

This outputs all contents at once by concatenating the string with newline character:

print('\n'.join(str(accessors[primitivie.attributes.POSITION]) for mesh in meshes for primitive in mesh.primitives))

Or decompress the generator into the print function and separate them with a newline character:

print(*(accessors[primitivie.attributes.POSITION] for mesh in meshes for primitive in mesh.primitives), sep='\n')

But it's best to use your original method. Compressing such a simple and readable behavior has no practical significance.

Upvotes: 1

smokey
smokey

Reputation: 21

If you want to have it as compact as possible use this.

lst = [accessors[primitive.attributes.POSITION] for mesh in meshes for primitive in mesh.primitives]

for a in lst: print(a)

Upvotes: 2

Related Questions