【问题标题】:List comprehension syntax error for appending word length to a list将单词长度附加到列表的列表理解语法错误
【发布时间】:2015-10-07 16:44:19
【问题描述】:

我试图将以下示例放入使用 Python 进行 NLP 的列表理解,第 3 章中的问题 10。我尝试了各种组合来尝试使这种理解发挥作用。我想在该单词的长度旁边显示“已发送”中的单词。

import nltk
sent =  sent = ['The', 'dog', 'gave', 'John', 'the', 'newspaper']
result = []

[word_len=(word, len(word)), result.append(word_len) for word in sent]
File "<stdin>", line 1
[word_len = (word, len(word)), result.append(word_len) for word in sent]
              ^

SyntaxError: 无效语法

或者 [word_len=(word, len(word)) result.append(word_len) for word in sent]

【问题讨论】:

  • 赋值不是列表理解的一部分。您期望产生什么输出?
  • 恐怕你的语法太远了。也许你需要re-read the tutorial

标签: python list-comprehension


【解决方案1】:

您不能在列表理解中进行赋值。您也不应该将其用于副作用(例如您的 result.append(word_len)

这里不要使用列表推导式。

sent = ['The', 'dog', 'gave', 'John', 'the', 'newspaper']

result = []
some_list = []

for word in sent:
    result.append(len(word))
    some_list.append((word, len(word))

或者,如果您所做的只是填充结果,则直接将其设为列表推导式。

result = [len(word) for word in sent]

要扩展“副作用”警告,您可以执行以下操作:

result = []

[result.append(len(word)) for word in sent]

这将根据您的需要填充result,但格式不正确。它在内存中创建了一个Nones 列表(因为list.append 总是返回None),它实际上并不需要存在。

【讨论】:

    【解决方案2】:

    我想你只是想要:

    [(word, len(word)) for word in sent]
    

    您的问题与 nltk 无关,只是纯粹的列表理解。

    【讨论】:

    • 我刚刚编辑掉了他们的 ntlk 标签并添加了 list-comprehension
    • 这正是我想做的理解,只需打印单词和长度,感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-31
    • 2013-08-15
    • 2019-11-06
    • 2018-09-28
    • 2013-01-16
    • 1970-01-01
    相关资源
    最近更新 更多