Python中列表理解的困难

2024-05-20 23:37:28 发布

您现在位置:Python中文网/ 问答频道 /正文

对于一个在线课程,我想创建一个名为censor的函数,它将两个字符串作为输入(文本和单词),并返回所选单词被星号替换的文本。 示例:

censor("this hack is wack hack", "hack")

应返回:

"this **** is wack ****"

使用for循环我得到了一个可操作的函数,但我想用列表理解来实现它,似乎不能使它起作用。你知道吗

def censor(text, word):
    words = text.split()
    result = ''
    censored = '*' * len(word)
    [censored if i == word else i for i in words]
    result =' '.join(words)
    return result

print censor("this hack is wack hack", "hack")

但是,底部的print函数只输出'this hack is wack hack'

我错过了什么?你知道吗


Tags: 函数text文本forisresultthis单词
3条回答

从你回来的时候往后退。返回结果。结果是“”连接(单词)。什么是语言?单词是单词=文本.拆分(). 你基本上忽略了其他的线路。你知道吗

def censor(text, word):
    return ' '.join(['*' * len(word) if x == word else x for x in text.split()])

print(censor("this hack is wack hack", "hack"))

这里

[censored if i == word else i for i in words]

你创建了一个经过审查的单词列表,但是你没有保留任何对它的引用。你知道吗

也许您想将这个列表赋回words变量

words = [censored if i == word else i for i in words]

因为你继续使用这个变量来生成你的返回值。你知道吗

首先, return语句不在函数体中。你知道吗

其次, 您需要将列表理解的结果存储到某个变量中。你知道吗

以下代码将起作用:

def censor(text, word):
    words = text.split()
    result = ''
    censored = '*' * len(word)
    result=[censored if i == word else i for i in words]
    return ' '.join(result)

print(censor("this hack is wack hack", "hack"))
this **** is wack ****

相关问题 更多 >