Why is this invalid syntax within for loop?
本问题已经有最佳答案,请猛点这里访问。
我尝试使用以下代码,但得到了错误:
1 2 3 4 | def preprocess(s): return (word: True for word in s.lower().split()) s1 = 'This is a book' text = preprocess(s1) |
然后出现了一个错误
1 | return (word: True for word in s.lower().split()) |
是无效语法。我找不到错误的来源。
我想将序列放入这个列表模型中:
1 | ["This": True,"is" : True,"a" :True,"book": True] |
您要构造一个字典而不是列表。使用大括号
1 2 3 4 | def preprocess(s): return {word: True for word in s.lower().split()} s1 = 'This is a book' text = preprocess(s1) |
您要做的是将序列放入字典,而不是列表。字典的格式为:
1 2 3 4 | dictionaryName={ key:value, key1:value1, } |
所以您的代码可以这样工作:
1 2 3 4 | def preprocess(s): return {word:True for word in s.lower().split()} s1 = 'This is a book' text = preprocess(s1) |