列表理解中的双重语句

时间:2017-11-03 22:41:01

标签: string python-3.x list list-comprehension

wordlist = ['cat','dog','rabbit']
letterlist = [ ]

要列出所有单词中的所有字符,我们可以这样做:

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

['c', 'a', 't', 'd', 'o', 'g', 'r', 'a', 'b', 'b', 'i', 't']

但是,当我尝试这样做时:

letterlist = [character for character in word for word in wordlist]

我收到错误:

NameError: name 'word' is not defined on line 9

有人可以解释我在理解列表理解如何工作方面的错误吗?

感谢。

1 个答案:

答案 0 :(得分:1)

写作

wordlist   = ["cat", "dog", "rabbit"]
letterlist = [character for character in word for word in wordlist]

与以下嵌套循环相当:

wordlist   = ["cat", "dog", "rabbit"]
letterlist = []

for character in word:

    for word in wordlist:

        letterlist.append(character)

此循环将抛出与列表理解相同的错误,因为您在将character in word定义为word的元素之前尝试引用wordlist。你只需要向后退货。请尝试以下方法:

letterlist = [character for word in wordlist for character in word]