【问题标题】:Why is this invalid syntax within for loop? [duplicate]为什么 for 循环中的这种无效语法? [复制]
【发布时间】:2018-10-30 04:00:24
【问题描述】:

我正在尝试使用以下代码并收到错误:

def preprocess(s):
    return (word: True for word in s.lower().split())
s1 = 'This is a book'
text = preprocess(s1)

然后出现的错误是

return (word: True for word in s.lower().split()) 

是无效的语法。我找不到错误的来源。

我想把序列放到这个列表模型中:

["This": True, "is" : True, "a" :True, "book": True]

【问题讨论】:

  • 这不是一个列表。你想要一本字典
  • 另外,如果你确实想要一个列表,你会使用[],而不是(),否则你只会返回一个生成器表达式。

标签: python


【解决方案1】:

您想构建字典而不是列表。请改用花括号 { 语法:

def preprocess(s):
    return {word: True for word in s.lower().split()}
s1 = 'This is a book'
text = preprocess(s1)

【讨论】:

    【解决方案2】:

    您要做的是将序列放入字典而不是列表中。 字典的格式是:

    dictionaryName={
        key:value,
        key1:value1,
    }
    

    所以你的代码可以这样工作:

    def preprocess(s):
        return {word:True for word in s.lower().split()}
    s1 = 'This is a book'
    text = preprocess(s1)
    

    【讨论】:

      猜你喜欢
      • 2021-11-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-09
      • 1970-01-01
      • 2019-03-16
      • 1970-01-01
      相关资源
      最近更新 更多