【问题标题】:AttributeError: 'list' object has no attribute 'replace' out = [j.replace("on", "re") for j in out]AttributeError: 'list' 对象没有属性 'replace' out = [j.replace("on", "re") for j in out]
【发布时间】:2020-11-29 16:21:55
【问题描述】:

我正在尝试用用户词替换这些词。这两个词都取自用户。但我不知道这是怎么回事。

def practiseeight():
    number = str(request.args.get('num'))
    on = str(request.args.get('one'))
    re = str(request.args.get('two'))
    value = number.split('<')
    print(value)
    out = []
    for i in value:
        i = i.split('>')
        out.append(i)
        print("This is",out)
        
     
    out = [j.replace("on", "re") for j in out]
    print("new list", out)

【问题讨论】:

  • 尝试打印out 中的值以查看它们是什么。 i = i.split('&gt;') 创建了一个列表,这就是列表中的内容。由于我们没有您的数据并且我们不知道替换应该做什么,所以我们无能为力。
  • 这是我对上述代码的输入

标签: python list for-loop replace attributeerror


【解决方案1】:

正如其他答案正确提到的那样,您的变量“out”成为列表列表,因为您将“i”(这是一个列表)附加到变量“out”中。尝试改用“out.extend”。

out = []
for i in value:
    i = i.split('>')
    out.extend(i)  ## this will add the element 'i' to the end of the existing list 'out'
    print("This is",out)
    
 
out = [j.replace("on", "re") for j in out]
print("new list", out)

【讨论】:

    【解决方案2】:

    代码中的问题:

    out = []
        for i in value:
            i = i.split('>') # so you are splitting i, split return a list
            out.append(i) # you are appending i which is a list
            print("This is",out)
        out = [j.replace("on", "re") for j in out] # now you are going through each element in out, each element is a list. List do not have replace, strings do!
    

    在列表中替换:

    out = [['abc'], ['abc', 'bcd']]
    for i in out: # go through each element in out
        for j,v in enumerate(i): i[j] = v.replace('b','e') # go through each element in the list of list and replace
    print(out)
    
    [['aec'], ['aec', 'ecd']]
    

    【讨论】:

    • @kuldeepSingSindhu 如果你有时间你能解释一下第二个for循环的详细理解吗(for j,v in enumerate(i): i[j] = v.replace('b',' e')) 将不胜感激。
    • enumerate 遍历列表并为您提供索引,该索引处的值。我们正在获取该值,对其进行替换,然后更新该索引处的列表。 j 上面是索引,v 是值。您可以打印它们以获得更好的想法!
    猜你喜欢
    • 1970-01-01
    • 2014-09-02
    • 2019-09-12
    • 2014-06-19
    • 1970-01-01
    • 2021-05-29
    • 2019-08-02
    • 2016-04-21
    • 2018-05-10
    相关资源
    最近更新 更多