我最近一直在练习使用 map()
在 Python 3.5.2 中,当我尝试运行模块时,它说逗号分隔函数和 iterable
是 SyntaxError
.这是代码:
eng_swe = {"merry":"god", "christmas":"jul", "and":"och", "happy":"gott",
"new":"nytt", "year":"år"}
def map_translate(l):
"""Translates English words into Swedish using the dictionary above."""
return list(map(lambda x: eng_swe[x] if x in eng_swe.keys(), l))
我注意到,如果我消除这样的条件语句:
return list(map(lambda x: eng_swe[x], l))
它工作正常,但它牺牲了避免尝试将不在字典中的项目添加到列表的能力。有趣的是,当我尝试使用带有
reduce()
的条件语句时也没有任何问题。 ,如此处所示:from functools import reduce
def reduce_max_in_list(l):
"""Returns maximum integer in list using the 'reduce' function."""
return reduce(lambda x, y: x if x > y else y, l)
是的,我知道我可以通过列表理解更简洁、更轻松地完成完全相同的事情,但我认为值得我花时间至少学习如何使用
map()
正确,即使我最终再也不会使用它。
最佳答案
您将获得 SyntaxError
因为您使用的是条件表达式而不提供 else
条款是强制性的。
The grammar对于条件表达式(即 if
表达式形式的语句)总是 包括 else
条款:
conditional_expression ::= or_test ["if" or_test "else" expression]
^^
在您的
reduce
以你为例做提供它,因此不会引发任何错误。
关于python - 为什么我收到此条件语句的语法错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38417677/