Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/303.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python一行if-else语句SyntaxError,错误位于;“否则”;,有什么问题吗? def-censor_字符串(txt、lst、char): 返回“.join”([char*len(i)表示txt.split()中的i,如果我在lst else i]) 打印(审查字符串(“奶牛跳过了月亮。”,[“奶牛”,“越过”],“*”))_Python_If Statement - Fatal编程技术网

Python一行if-else语句SyntaxError,错误位于;“否则”;,有什么问题吗? def-censor_字符串(txt、lst、char): 返回“.join”([char*len(i)表示txt.split()中的i,如果我在lst else i]) 打印(审查字符串(“奶牛跳过了月亮。”,[“奶牛”,“越过”],“*”))

Python一行if-else语句SyntaxError,错误位于;“否则”;,有什么问题吗? def-censor_字符串(txt、lst、char): 返回“.join”([char*len(i)表示txt.split()中的i,如果我在lst else i]) 打印(审查字符串(“奶牛跳过了月亮。”,[“奶牛”,“越过”],“*”)),python,if-statement,Python,If Statement,你必须写 def censor_string(txt, lst, char): return " ".join([char*len(i) if i in lst else i for i in txt.split() ]) print(censor_string("The cow jumped over the moon.", ["cow", "over"], "*")) 给你: de

你必须写

def censor_string(txt, lst, char):
    return " ".join([char*len(i) if i in lst else i for i  in txt.split() ])
print(censor_string("The cow jumped over the moon.", ["cow", "over"], "*"))
给你:

def-censor_字符串(txt、lst、char):
返回“”
打印(审查字符串(“奶牛跳过了月亮。”,[“奶牛”,“越过”],“*”))
输出

The *** jumped **** the moon.

有两个地方可以在列表中放置条件:

[ AA or BB for elem in sequence if elem something]
  ^^^^^^^^^^                      ^^^^^^^^^^^^^^^^^-- use the element or not in the 
           ^--- what to put into the result           result - no ELSE allowed
所以你的正确版本应该是

def censor_string(txt, lst, char):
    return " ".join([char*len(i) if i in lst else i for i in txt.split()])
print(censor_string("The cow jumped over the moon.", ["cow", "over"], "*"))
得到

The *** jumped **** the moon.

列表理解语法如下所示:

[expression for ... in iterable if something]
if
子句是可选的,仅用于过滤。所以你不能在那里有一个
else
。但是,您可以控制表达式。条件表达式也是表达式,因此您可以编写如下内容:

def censor_string(txt, lst, char):
    return " ".join([char*len(i) if i in lst else i for i in txt.split()])

print(censor_string("The cow jumped over the moon.", ["cow", "over"], "*"))
要达到预期效果,请执行以下操作:

The *** jumped **** the moon. 那个男孩跳到了月球上。
这和另一个答案不一样吗?@OlvinRoght似乎是。但是,在我发布我的答案之前,我对其他代码一无所知。@OlvinRoght我投了反对票,因为它没有解释问题是什么以及如何解决问题。“你必须写这个”不应该被认为是有效的解释。大多数时候,像这样的帖子上的否决票根本没有任何作用,因为如果一个正确的答案被否决,人们倾向于投上一票。