理解python嵌套一行for循环

时间:2015-05-09 00:21:38

标签: python for-loop nested-loops

我试图理解一行for循环并将其置于嵌套for循环的正常命名法中。单线for循环如下:

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

我用传统的方式编写了上面嵌套的for循环,如下所示:

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

我没有得到理想的结果。有人可以解释我的想法出错的地方,或者上面的单行for循环如何能够按常规编写。提前谢谢。

2 个答案:

答案 0 :(得分:3)

仔细查看单行中的括号:

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

嵌套生成器只是一个为外部生成器提供值的序列。它可以简化为

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

或只是

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

等效循环

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

答案 1 :(得分:1)

嵌套循环简化示例。

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']

第一步:

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

第二步:

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

第三步:

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

结果相同:

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