Python 为什么for循环中的语法无效?

Python 为什么for循环中的语法无效?,python,Python,我尝试使用以下代码时出错: 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,

我尝试使用以下代码时出错:

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]

您想要构造一个字典而不是一个列表。请改用大括号
{
语法:

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

您希望构造字典而不是列表。请改用大括号
{
语法:

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

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

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)

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

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)

这不是一个列表。你想要一个字典。因此,如果你想要一个列表,你应该使用
[]
,而不是
()
,否则你只会返回一个生成器表达式。那不是一个列表。你想要一个字典。如果你想要一个列表,你应该使用
[]
,而不是
()
,否则你只会返回一个生成器表达式。