嵌套列表推导中的违反直觉的行为

时间:2016-05-24 22:31:26

标签: python-2.7 list-comprehension nested-loops

我在嵌套列表推导上遇到了一些违反直觉的行为

data = 'what is wrong with the nested iterator'
[ (u, i) for i in xrange(0,len(u),1) for u in [ v for v in data.split(' ')]]

我希望嵌套循环会迭代第一个循环中每个单词的字符范围。然而,正在发生的事情似乎是首先循环字符串数组,并迭代u的最后一个值:

[('what', 0), ('is', 0), ('wrong', 0), ('with', 0), ('the', 0), ('nested', 0), ('iterator', 0), ('what', 1), ('is', 1), ('wrong', 1), ('with', 1), ('the', 1), ('nested', 1), ('iterator', 1), ('what', 2), ('is', 2), ('wrong', 2), ('with', 2), ('the', 2), ('nested', 2), ('iterator', 2), ('what', 3), ('is', 3), ('wrong', 3), ('with', 3), ('the', 3), ('nested', 3), ('iterator', 3), ('what', 4), ('is', 4), ('wrong', 4), ('with', 4), ('the', 4), ('nested', 4), ('iterator', 4), ('what', 5), ('is', 5), ('wrong', 5), ('with', 5), ('the', 5), ('nested', 5), ('iterator', 5), ('what', 6), ('is', 6), ('wrong', 6), ('with', 6), ('the', 6), ('nested', 6), ('iterator', 6), ('what', 7), ('is', 7), ('wrong', 7), ('with', 7), ('the', 7), ('nested', 7), ('iterator', 7)]

1 个答案:

答案 0 :(得分:1)

要理解这些嵌套类型的列表推导,您可以将它们想象为两个嵌套的for循环,如下所示:

result = []
for i in xrange(0,len(u),1):
    for u in [ v for v in data.split(' '):
        result.append((u, i))

保留两个循环的顺序。从这一点来看,你应该很清楚,你需要切换他们的位置才能获得理想的结果。