【问题标题】:Why does one function work while the other doesn't?为什么一个功能起作用而另一个不起作用?
【发布时间】:2014-03-03 05:34:11
【问题描述】:

通过 codeacademy for python,一项任务是编写一个函数,该函数将接受一个字符串并用星号删去某个单词,然后返回该字符串。我尝试了一种方法,但它没有用,但我又尝试了另一种方法,它成功了。我只是好奇为什么。

那个没用的:

def censor(text, word):
    split_string = text.split()
    replace_string = "*" * len(word)
    for i in split_string:
        if i == word:
            i = replace_string 
    return " ".join(split_string)

确实有效的那个:

def censor(text, word):
    split_string = text.split()
    replace_string = "*" * len(word)
    for i in range(0, len(split_string)):
        if split_string[i] == word:
            split_string[i] = replace_string
    return " ".join(split_string)

【问题讨论】:

    标签: python python-2.7


    【解决方案1】:
    def censor(text, word):
        split_string = text.split()
        replace_string = "*" * len(word)
        for i in split_string:
            if i == word:
                i = replace_string # This doesn't work*
        return " ".join(split_string)
    

    这不起作用,因为您所做的只是将名称i 分配给另一个字符串。相反,您可以构建一个新列表,或者像在第二个示例中所做的那样替换原始列表中的字符串。

    【讨论】:

      【解决方案2】:

      下面的语句使得i引用了replace_string引用的值,并且不影响列表项。

      i = replace_string
      

      >>> lst = [1, 2, 3]
      >>> i = lst[0]
      >>> i = 9
      >>> i   # affects `i`
      9
      >>> lst # but does not affect the list.
      [1, 2, 3]
      

      同时,lst[<number>] = replace_string 就地更改列表项。

      >>> lst[0] = 9
      >>> lst
      [9, 2, 3]
      

      【讨论】:

        猜你喜欢
        • 2021-06-10
        • 2011-03-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多