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

标签 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))]

不过我的第一个方案好像也对,谁能告诉我为什么第一个方案不行?

最佳答案

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

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 is not defined”错误而失败的原因是您将 word 变量定义为 rabbit 在范围内:

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

关于python - 为什么这个列表理解不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39794590/

相关文章:

python - Django 休息框架用户注册?

Python 分析 : using line_profiler's @profile decorator results in error

python - 如何将 linecache 与 unicode 一起使用?

Python:列表中完整字符串与部分字符串的交集

python - 如何根据 if 语句的结果缩短附加到不同列表的时间

c++ - 合并两个不重复的链表

python - C# Unity - 从统一的相机中提取像素数组并在 python 中显示

Python 子进程包返回损坏的管道

python - 如何创建一个对两个或多个相同形状的嵌套列表进行操作的 Python 函数?

c - 填充单链表节点