deep
deep

Reputation: 716

Understanding python nested one line for loops

I am trying to understand one line for-loops and putting it in to normal nomenclature for nested for-loops. The one-liner for-loops is as follows:

print ''.join((letter[i - 1]for i in (int(n) for n in key.split())))

I wrote the above nested for-loops in a conventional way as follows:

for n in key.split():
    n = int(n)
    for i in n:
        print ''.join(letter[i - 1])

I am not getting the desired result. Please can someone explain where my thinking is going wrong or how can the above one-line for-loops can be written conventionally. Thanks in advance.

Upvotes: 2

Views: 6177

Answers (2)

iperov
iperov

Reputation: 514

Example of nested loops simplification.

from enum import IntEnum

class MyEnum(IntEnum):
    FOO_BAR = 0
    JOHN_DOE = 1
    
result = []
for x in MyEnum:
    x_splits = []
    for s in x.name.split('_'):
        x_splits.append( s.capitalize() )    
    result.append ( ' '.join(x_splits) )
    
# >>> result
# ['Foo Bar', 'John Doe']

First step:

result = []
for x in MyEnum:
    x_splits = [ s.capitalize() for s in x.name.split('_') ]
    result.append ( ' '.join(x_splits) )

Second step:

result = []
for x in MyEnum:
    result.append ( ' '.join( s.capitalize() for s in x.name.split('_') ) )

Third step:

result = [ ' '.join( s.capitalize() for s in x.name.split('_') ) for x in MyEnum ]

result the same:

# ['Foo Bar', 'John Doe']

Upvotes: 1

chepner
chepner

Reputation: 530940

Look carefully at the parentheses in your one-liner:

print ''.join((letter[i - 1]for i in (int(n) for n in key.split())))
                                     ^---------------------------^

The nested generator is simply a sequence that provides values for the outer generator. It could be simplified to

print ''.join((letter[int(i) - 1]for i in (n for n in key.split())))

or just

print ''.join(letter[int(i) - 1] for i in key.split())

An equivalent loop would be

for i in key.split():
    print letter[int(i) - 1],    # Suppress the newline

Upvotes: 3

Related Questions