为什么这个列表理解不起作用?

时间:2016-09-30 15:03:33

标签: python list

代码的目的是收集wordlist中的所有字符,我做了以下内容:

wordlist = ['cat','dog','rabbit']
[c for c in word for word in wordlist]

输出很奇怪:

['r',
 'r',
 'r',
 'a',
 'a',
 'a',
 'b',
 'b',
 'b',
 'b',
 'b',
 'b',
 'i',
 'i',
 'i',
 't',
 't',
 't']

我知道我可以使用:

[ch for ch in "".join(wordlist)]

[word[i] for word in wordlist for i in range(len(word))]

然而,我的第一个建议似乎也是对的,任何人都可以告诉我为什么第一个提案不起作用?

2 个答案:

答案 0 :(得分:3)

问题在于理解中for语句的 order ,它们必须交换:

In [10]: [c for word in wordlist for c in word]
Out[10]: ['c', 'a', 't', 'd', 'o', 'g', 'r', 'a', 'b', 'b', 'i', 't']

请注意,它为您工作的原因并没有因“word未定义”错误而失败,因为您在范围内将word变量定义为rabbit:< / p>

In [3]: [c for c in word for word in wordlist]
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-7-decfecd23a92> in <module>()
----> 1 [c for c in word for word in wordlist]

NameError: name 'word' is not defined
In [4]: word = 'rabbit'

In [5]: [c for c in word for word in wordlist]
Out[5]: 
['r',
 'r',
 'r',
 'a',
 'a',
 'a',
 'b',
 'b',
 'b',
 'b',
 'b',
 'b',
 'i',
 'i',
 'i',
 't',
 't',
 't']

答案 1 :(得分:2)

您的for语句的顺序错误:

[c for c in word for word in wordlist]

应该是

[c for word in wordlist for c in word]

在列表解析中记住for语句顺序的方法是想象如何将其作为循环编写。订单遵循缩进:

result = []
for word in wordlist:
    for c in word:
        result.append(c)