【问题标题】:why use index over replace? [closed]为什么使用索引而不是替换? [关闭]
【发布时间】:2022-01-22 09:46:51
【问题描述】:

我试图在此链接上执行任务 9: https://pynative.com/python-list-exercise-with-solutions

我理解他们为什么选择以他们的方式解决问题,但为什么我会收到此错误,我选择的方式是否相关?

我的代码:

list1 = [5, 10, 15, 20, 25, 50, 20]
list.replace('20', '200', 3)
print (list1)

错误:

"C:\Users\yammeir\PycharmProjects\ifelse q\venv\Scripts\python.exe" "C:/Users/yammeir/PycharmProjects/ifelse q/main.py"
Traceback (most recent call last):
  File "C:\Users\yammeir\PycharmProjects\ifelse q\main.py", line 3, in <module>
    list.replace('20', '200', 3)
AttributeError: type object 'list' has no attribute 'replace'

Process finished with exit code 1

【问题讨论】:

  • 您好,欢迎来到 SO。您看到的错误是因为 python 中的列表没有以与字符串相同的方式附加到它们的方法/函数replace()。所以,你必须找到另一种方法来获得你想要的东西。

标签: python attributeerror


【解决方案1】:

list 没有replace 方法,因此您的代码无法运行。

【讨论】:

  • ^ 你的数组也是 list1 而不是 list
  • @B.Quinn True 'dat
【解决方案2】:
嗯,在Python中,列表没有称为replace的属性。但是,您可以像这样定义 replace 函数:
def replace(my_list, a, b):
    my_list[my_list.index(a)] = b
    return my_list

其中ab 987654325 @的数组中的值(第一次出现)。

现在,您可以像这样调用你的函数:

list = [5, 10, 15, 20, 25, 50, 20]
list = replace(list, 10, 11)
print(list)   # [5, 11, 15, 20, 25, 50, 20]

【讨论】:

    【解决方案3】:

    list 没有 .replace 方法。另外,您在 list 而不是 list1 上调用 .replace 方法。如果要替换列表中的某些内容,只需执行以下操作:

    #        0, 1,  2,  3 
    list1 = [5, 10, 15, 20, 25, 50, 20]
    list1[3] = 200
    print(list1)
    

    输出:

    [5, 10, 15, 200, 25, 50, 20]
    

    我们只是为列表中的第 4 位分配了 200 的值。

    .replace 方法用于字符串。例如,如果list1 被替换为string1

    string1 = "5, 10, 15, 20, 25, 50, 20"
    print(string1.replace('20', '200', 3))
    

    输出:

    5, 10, 15, 200, 25, 50, 200
    

    有关.replace 方法的更多信息: https://www.tutorialspoint.com/python/string_replace.htm

    【讨论】:

      猜你喜欢
      • 2015-06-03
      • 2015-04-26
      • 2011-07-08
      • 2011-12-08
      • 2011-09-25
      • 2015-12-04
      • 2020-12-04
      相关资源
      最近更新 更多