4 回答
TA贡献1830条经验 获得超9个赞
我希望这对别人a,b,x,y有帮助,因为对我没有太大的意义!假设您有一个充满句子的文本,并且想要一个单词数组。
# Without list comprehension
list_of_words = []
for sentence in text:
for word in sentence:
list_of_words.append(word)
return list_of_words
我喜欢将列表理解理解为水平扩展代码。
尝试将其分解为:
# List Comprehension
[word for sentence in text for word in sentence]
例:
>>> text = (("Hi", "Steve!"), ("What's", "up?"))
>>> [word for sentence in text for word in sentence]
['Hi', 'Steve!', "What's", 'up?']
这也适用于发电机
>>> text = (("Hi", "Steve!"), ("What's", "up?"))
>>> gen = (word for sentence in text for word in sentence)
>>> for word in gen: print(word)
Hi
Steve!
What's
up?
TA贡献1824条经验 获得超8个赞
e,我想我找到了答案:我对那个循环是内部的,哪个循环是外部的,没有足够的小心。列表理解应为:
[x for b in a for x in b]
为了获得期望的结果,是的,一个当前值可以作为下一个循环的迭代器。
添加回答
举报