【问题标题】:AttributeError: 'dict' object has no attribute 'append' on line 9?AttributeError:'dict' 对象在第 9 行没有属性'append'?
【发布时间】:2020-11-07 21:51:02
【问题描述】:

Q.)8.4 打开文件 romeo.txt 并逐行读取。对于每一行,使用 split() 方法将该行拆分为一个单词列表。该程序应该建立一个单词列表。对于每行上的每个单词,检查该单词是否已经在列表中,如果没有,则将其附加到列表中。程序完成后,按字母顺序对生成的单词进行排序和打印。 此代码给出 AttributeError: 'dict' object has no attribute 'append' on line 9

    fname = input("Enter file name: ")
        fh = open(fname)
        lst = {}
        for line in fh:
            line = line.rstrip()
            words = line.split()
            for word in words:
                if word not in lst:
                    lst.append(word)
        print(sorted(lst))

【问题讨论】:

    标签: list split append


    【解决方案1】:

    Python 字典没有append 方法。

    Append 用于 Python 中的列表(数组)。将lst 设为列表,而不是字典。我在你下面的代码中做了一个小的改动,改变了

    lst = {}   #creation of an empty dictionary 
    

    lst = []    #creation of an empty list
    

    完整代码:

    fname = input("Enter file name: ")
            fh = open(fname)
            lst = []
            for line in fh:
                line = line.rstrip()
                words = line.split()
                for word in words:
                    if word not in lst:
                        lst.append(word)
            print(sorted(lst))
    
    

    【讨论】:

    • 在投票之前,我对您的答案进行了重大修改,以突出空列表/字典创建之间的区别。如果您认为它太侵入性,请随时恢复它。
    猜你喜欢
    • 2019-03-31
    • 2018-06-22
    • 1970-01-01
    • 2019-03-11
    • 2016-02-11
    • 2020-10-16
    • 2018-03-17
    • 2018-09-02
    • 2021-01-30
    相关资源
    最近更新 更多