0

在我的新手尝试并尝试编写许多小脚本并学习时;我遇到了这个困惑:

import re

nouns = ['bacon', 'cheese', 'eggs', 'milk']
article = []

def list_in_list(list1, list2):
    for list_1_element in list1:
        print list_1_element
    for list_2_element in list2:
        print list_2_element


with open('test_sentence.txt', 'r') as input_f:
    for line in input_f:
        article.append(re.findall(r"[\w']+|[.,!?;:]", line))
        list_in_list(article, nouns)

以下是 test_sentence.txt 的内容:

I need to go shopping today and some of the things I need to buy are bacon, cheese and eggs. I also need to buy something with a comma in it, such as milk, cheese, and bacon.

我不明白的是为什么print list_1_element实际打印整个 'list1' 列表,例如['I', 'need', 'to', 'go'.............]. print list_2_element正如我所料,实际将该列表的每个元素打印在新行上。

那么为什么会有差异呢?

4

2 回答 2

2

article.append([some list]) 将列表追加为一项

article.extend([some list]) 会将某个列表中的每个项目附加到文章列表中

于 2013-09-19T17:50:09.427 回答
1

因为article是一个包含单个项目的列表。您每行添加一个列表列表,并且您有一行。

于 2013-09-19T17:47:39.283 回答