首页 > 解决方案 > 在Python中组合列表时如何避免Nonetype

问题描述

我对 Python 很陌生,正在寻求帮助,以解决我在作业中出错的地方。我尝试了不同的方法来解决这个问题,但一直卡在同一点:

问题 1:当我尝试从文件中创建单词列表时,我一直在为每行而不是整个文件创建单词列表

问题 2:当我尝试合并列表时,我的结果或 Nonetype 错误一直收到“None”[我认为这意味着我已经将 None 添加在一起(?)]。

任务是:

#8.4 Open the file romeo.txt and read it line by line. For each line, split the line into a list of words using the split() method. The program should build a list of words. For each word on each line check to see if the word is already in the list and if not append it to the list. When the program completes, sort and print the resulting words in alphabetical order.You can download the sample data at http://www.py4e.com/code3/romeo.txt

我当前给我 Nonetype 错误的代码是:

poem = input("enter file:")
play = open(poem)
lst= list()
for line in play:
    line=line.rstrip()
    word=line.split()
    if not word in lst:
        lst= lst.append(word)
print(lst.sort())

如果有人能告诉我我哪里出错了,那将不胜感激!

标签: pythonlistsplitnonetype

解决方案


只是为了帮助您更多地了解 Python:

您可以: 1. 一次读取整个文件(如果文件很大,如果有足够的文件,最好将其抓取到 RAM 中,如果没有尽可能多地抓取以使块合理,则抓取另一个文件并依此类推) 2. 将您读入的数据拆分为单词和 3. 使用 set() 或 dict() 删除重复项

一路走来,你不应该忘记注意大小写,如果你需要相同的单词,而不仅仅是不同的不重复的字符串

只要您在 Py2 中对 input() 函数执行一些操作或在输入路径时使用引号,这将在 Py2 和 Py3 中起作用,因此:

path = input("Filename: ")
f = open(filename)
c = f.read()
f.close()
words = set(x.lower() for x in c.split()) # This will make a set of lower case words, with no repetitions
# This equals to:
#words = set()
#for x in c.split():
#    words.add(x.lower())
# set() is an unordered datatype ignoring duplicate items
# and it mimics mathematical sets and their properties (unions, intersections, ...)
# it is also fast as hell.
# Checking a list() each time for existance of the word is slow as hell
#----
# OK, you need a sorted list, so:
words = sorted(words)
# Or step-by-step:
#words = list(words)
#words.sort()
# Now words is your list

至于您的错误,请不要担心,它们在开始时几乎在任何面向目标的语言中都很常见。其他人在他们的评论中很好地解释了他们。但不要让答案缺乏......:

始终注意对数据类型进行操作的函数或方法(就地排序 - list.sort()、list.append()、list.insert()、set.add()...)以及哪些返回新的数据类型的版本(sorted()、str.lower()...)。如果您再次遇到类似情况,请在交互式 shell 中使用 help() 来查看您使用的函数究竟做了什么。

>>> help(list.append)
>>> help(list.sort)
>>> help(str.lower)
>>> # Or any short documentation you need

Python,尤其是 Python 3.x 对尝试类型之间的操作很敏感,但有些可能有不同的内涵,并且可以在做意想不到的事情时实际工作。例如,您可以这样做:

print(40*"x")

它将打印出 40 个“x”字符,因为它将创建一个 40 个字符的字符串。但:

print([1, 2, 3]+None)

将,逻辑上不起作用,这就是你代码的其余部分发生的事情。

在某些语言中,例如 javascript(可怕的东西),这将非常有效:

v = "abc "+123+" def";

将 123 无缝插入字符串中。这很有用,但从另一个角度来看,这是一场编程噩梦和胡说八道。

此外,在 Py3 中,来自 Py2 的一个合理假设是,您可以混合 unicode 和字节字符串并且将执行自动转换是不成立的。即这是一个类型错误:

print(b"abc"+"def")

因为在 Py3 中 b"abc" 是 bytes() 而 "def" (或 u"def")是 str() - Py2 中的 unicode() 是什么)

享受 Python,它是最好的!


推荐阅读