Skip to main content
 首页 » 编程设计

python之为什么这个 List 会插入一个嵌套的 List

2025年05月04日9hnrainll

这里是一个简单的问题;我在名为 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 返回每一行的列表。由于您将 row 添加到 stops,因此您将列表添加到列表。为防止这种情况,您可以使用:

stops.extend(row) 

或者更好的是,使用列表理解:

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