获取无效语法,我不确定为什么
Getting invalid syntax, and I'm not sure why
这是我的代码:
total = 0
s = "helloV"
for i in range(0, len(s)):
total += 4 if s[i] == "V" else (total += 9) # The line where I'm getting the syntax error.
我不确定这段代码为什么会出现语法错误。任何帮助将不胜感激。
代码应该是这样的:
total = 0
s = "helloV"
for i in range(0, len(s)):
total += 4 if s[i] == "V" else 9
当 if 条件为真时添加 4
否则添加 9
.
如果您正在寻找更短的代码,您也可以这样做。如果 s
中的字符不等于 'V'
,它只使用列表推导式生成一个列表,如果 s
中的字符不等于 'V'
,则列表包含 4
。然后,它只是将结果列表与 sum()
:
相加
s = "helloV"
total = sum([4 if i == 'V' else 9 for i in s])
或者您可以使用 map()
将 lambda
函数应用于 s
的每个元素,其作用与上述相同:
s = "helloV"
total = sum(map(lambda i: 4 if i == 'V' else 9, s))
total = 0
s = "helloV"
for i in range(0, len(s)):
if s[i] == "V":
total += 4
else:
total += 9
以上是解决语法问题的清晰方法。
这是我的代码:
total = 0
s = "helloV"
for i in range(0, len(s)):
total += 4 if s[i] == "V" else (total += 9) # The line where I'm getting the syntax error.
我不确定这段代码为什么会出现语法错误。任何帮助将不胜感激。
代码应该是这样的:
total = 0
s = "helloV"
for i in range(0, len(s)):
total += 4 if s[i] == "V" else 9
当 if 条件为真时添加 4
否则添加 9
.
如果您正在寻找更短的代码,您也可以这样做。如果 s
中的字符不等于 'V'
,它只使用列表推导式生成一个列表,如果 s
中的字符不等于 'V'
,则列表包含 4
。然后,它只是将结果列表与 sum()
:
s = "helloV"
total = sum([4 if i == 'V' else 9 for i in s])
或者您可以使用 map()
将 lambda
函数应用于 s
的每个元素,其作用与上述相同:
s = "helloV"
total = sum(map(lambda i: 4 if i == 'V' else 9, s))
total = 0
s = "helloV"
for i in range(0, len(s)):
if s[i] == "V":
total += 4
else:
total += 9
以上是解决语法问题的清晰方法。