简体   繁体   English

Python似乎自动将列表转换为字符串,之后.append()和.pop()不可用

[英]Python seems to automatically convert a list to a string, after which .append() and .pop() are unusable

I'm using Python 3.6 and PyCharm if that matters at all. 如果很重要,我正在使用Python 3.6和PyCharm。 I'm also fairly new to Python programming (especially working with files) so sorry if I'm missing something obvious. 我对Python编程(尤其是使用文件)也很陌生,如果我遗漏了一些明显的东西,请抱歉。

I am trying to make a script that writes the first 20 items from the look-and-say sequence into a file, each item on a separate line. 我正在尝试编写一个脚本,将外观序列中的前20个项目写入文件,每个项目都放在单独的行上。 The script works fine for the first 4 lines, however, raises an exception afterwards. 该脚本在前4行中运行良好,但是此后会引发异常。

LINES = 20
with open("sequence.txt", "r+") as finalOutput:
    finalOutput.truncate(0)
    finalOutput.write("1")
    for i in range(LINES-1):
        finalOutput.seek(0)
        prevLine = finalOutput.readlines()[-1]
        newLine = ""
        block = []
        for c in prevLine:
            if c == "\n":
                break
            else:
                block.append(c)
                if block[-1] != block[0]:
                    newLine += str(len(block[:-1]))
                    newLine += str(block[0])
                    block = block.pop()
        if len(block) != 0:
            newLine += str(len(block))
            newLine += str(block[0])
        finalOutput.write("\n" + newLine)

After "1211" is written into the file, I'm presented with the following error: 将“ 1211”写入文件后,出现以下错误:

Traceback (most recent call last):
  File "C:/Users/ViAik/PycharmProjects/1_11_21_1211_sequence/main.py", line 
14, in <module>
    block.append(c)
AttributeError: 'str' object has no attribute 'append'

Which implies that block is a string, even though it started out as a list (?). 这意味着该block是一个字符串,即使它以列表(?)开头。 What confuses me the most is that the first 4 lines work properly. 最让我感到困惑的是前4行工作正常。

I am not even sure how to formulate my actual question here because I don't understand what's actually going on. 我什至不知道如何在这里提出我的实际问题,因为我不知道实际发生了什么。 I suppose that figuring that out is my question, and hopefully I can fix this code in a way that doesn't involve purposefully using block as a string. 我想弄清楚这是我的问题,希望我可以以不涉及故意将block用作字符串的方式修复此代码。 Any help? 有什么帮助吗? Thanks in advance. 提前致谢。

block = block.pop()

This makes block become it's own last element, which is a string. 这使得block成为它自己的最后一个元素,它是一个字符串。 I'm not sure what you expect to happen here. 我不确定您希望在这里发生什么。

eg 例如

block = ['hello', 'world']
block = block.pop()
print(block)  # --> world

Python works on the concept of reference object. Python处理引用对象的概念。 Variable names are references to the actual object. 变量名称是对实际对象的引用。 When a name is on the right hand side of an equation, the object that it references is automatically looked up and used in the equation. 当名称在方程式的右侧时,它所引用的对象将自动查找并在方程式中使用。 So when you write: 所以当你写:

 block = [] # the name block is a reference to a list

But when you again reference name block to a new object, it will point to the last reference object it assign. 但是,当您再次引用名称块到新对象时,它将指向它分配的最后一个引用对象。

block = block.pop() # the name block is a reference to string object.

So when you try to append an element in block it gives you error. 因此,当您尝试在块中附加元素时,会出现错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM