Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/338.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 为什么此列表会插入嵌套列表?_Python_List - Fatal编程技术网

Python 为什么此列表会插入嵌套列表?

Python 为什么此列表会插入嵌套列表?,python,list,Python,List,这里有一个简单的问题;我在一个名为stop_words.txt的CSV文本文件中有一个停止词列表 我正在使用此代码将这些添加到列表中: >>> import csv >>> stops = [] >>> with open('/stop_words.txt', 'rU') as f: reader = csv.reader(f) for row in reader: stops.append(row) 问题是

这里有一个简单的问题;我在一个名为stop_words.txt的CSV文本文件中有一个停止词列表

我正在使用此代码将这些添加到列表中:

>>> import csv
>>> stops = []
>>> with open('/stop_words.txt', 'rU') as f:
    reader = csv.reader(f)
    for row in reader:
        stops.append(row)
问题是当我跑步的时候

>>> len(stops)
1
我得到的长度是1。内容如下:

>>> stops
[['a', 'able', 'about', 'across', 'after', 'all', 'almost', 'also', 'am', 'among', 'an', 'and', 'any', 'are', 'as', 'at', 'be', 'because', 'been', 'but', 'by', 'can', 'cannot', 'could', 'dear', 'did', 'do', 'does', 'either', 'else', 'ever', 'every', 'for', 'from', 'get', 'got', 'had', 'has', 'have', 'he', 'her', 'hers', 'him', 'his', 'how', 'however', 'i', 'if', 'in', 'into', 'is', 'it', 'its', 'just', 'least', 'let', 'like', 'likely', 'may', 'me', 'might', 'most', 'must', 'my', 'neither', 'no', 'nor', 'not', 'of', 'off', 'often', 'on', 'only', 'or', 'other', 'our', 'own', 'rather', 'said', 'say', 'says', 'she', 'should', 'since', 'so', 'some', 'than', 'that', 'the', 'their', 'them', 'then', 'there', 'these', 'they', 'this', 'tis', 'to', 'too', 'twas', 'us', 'wants', 'was', 'we', 'were', 'what', 'when', 'where', 'which', 'while', 'who', 'whom', 'why', 'will', 'with', 'would', 'yet', 'you', 'your']]
这里有一个列表,但我不明白为什么


非常感谢。

csv.reader
返回每行的列表。由于将
添加到
停止
,因此将列表添加到列表中。要防止出现这种情况,您可以使用:

stops.extend(row)
或者更好的是,使用列表理解:

stops = [item for row in reader for item in row]

csv.reader
返回每行的列表。由于将
添加到
停止
,因此将列表添加到列表中。要防止出现这种情况,您可以使用:

stops.extend(row)
或者更好的是,使用列表理解:

stops = [item for row in reader for item in row]

您的csv阅读器将在逗号上拆分您的行,并返回一个列表。然后将该列表(作为单个元素)添加到
行中。相反,遍历返回的行并将每个条目添加到停止词列表中。

您的csv阅读器将在逗号上拆分您的行,并返回一个列表。然后将该列表(作为单个元素)添加到
行中。而是遍历返回的行,并将每个条目添加到停止词列表中。

我假设CSV文件中只有一行,这是所有停止词的列表。您试图构建一个“行”列表,其中一行是一个列表。这就是正在发生的事情;只有一排。由于只有一行,您可以将
停止
分配给csv中的第一行。

我假设csv文件中只有一行,这是所有停止字的列表。您试图构建一个“行”列表,其中一行是一个列表。这就是正在发生的事情;只有一排。由于只有一行,您可以将
停止
分配给csv中的第一行。

这看起来像您的
停止_words.txt
文件是一条长线。您可以直接使用此列表:

with open('/stop_words.txt', 'rU') as f:
    stops = next(csv.reader(f))

这看起来像您的
stop_words.txt
文件是一条长线。您可以直接使用此列表:

with open('/stop_words.txt', 'rU') as f:
    stops = next(csv.reader(f))

我已经更新了我的答案,向您展示了首选(最具Pythonic)方法。我已经更新了我的答案,向您展示了首选(最具Pythonic)方法。