简体   繁体   English

读取文件内容时在列表中创建列表的程序

[英]Program creating a list within a list when reading contents of file

I have found a fix for the following problem, however I'd like to understand why my below code creates a list of strings within a list, ie has this list of strings as the only element in an outer list.我找到了解决以下问题的方法,但是我想了解为什么我的以下代码会在列表中创建字符串列表,即将此字符串列表作为外部列表中的唯一元素。

I have a.txt file which I'm reading in which consists of about 25 sentences.我有一个我正在阅读的 .txt 文件,其中包含大约 25 个句子。 It is just one long paragraph and so I wanted to split it into sentences, delimited by a full stop.这只是一个很长的段落,所以我想把它分成几个句子,用句号分隔。 I initially used this code to perform this step:我最初使用此代码执行此步骤:

file = open("love_life.txt", "r")

list_of_sentences = []
for line in file:
    new = line.split('.')
    list_of_sentences.append(new)
file.close()
print(list_of_sentences)

I expected that this would create a list of strings, with each string representing a sentence delimited by a full stop.我希望这会创建一个字符串列表,每个字符串代表一个由句号分隔的句子。 But instead, although it indeed created a list of strings/sentences it did so enclosed within another list.但是,尽管它确实创建了一个字符串/句子列表,但它确实包含在另一个列表中。 So when I tried to iterate over the list, I was just iterating one time over the nested list.因此,当我尝试迭代列表时,我只是在嵌套列表上迭代了一次。 Like this output:像这个output:

[["lifeguards save lives", "time is of the essence", "the wind blows where it wants"]]

Can anyone tell me why this is happening with this code?谁能告诉我为什么这段代码会发生这种情况?

It's because line.split('.') returns a list, and list_of_sentences.append(new) adds that list to list_of_sentences .这是因为line.split('.')返回一个列表,而list_of_sentences.append(new)将该列表添加到list_of_sentences Maybe you meant to use list_of_sentences.extend(new) instead?也许您打算改用list_of_sentences.extend(new) That would add each element of new to list_of_sentences .这会将new每个元素添加到list_of_sentences

You should use extend() , if you dont want to end up with a list of list.如果您不想得到一个列表列表,您应该使用extend()

    file = open("love_life.txt", "r")

    list_of_sentences = []
    for line in file:
        new = line.split('.')
        list_of_sentences.append(new)
    file.close()
    print(list_of_sentences)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM