[英]How to split an integer list into two separate lists that are around the same average? -Python
[英]Python - How to split a list into two separate lists dynamically
我正在使用Python-3,正在读取一个文本文件,该文件可以包含多个用'\\ n'分隔的段落。 我想将所有这些段落分成一个单独的列表。 输入文件中可以有n个段落。
因此,此拆分和输出列表的创建应动态进行,从而使我可以通过仅将段落编号输入为list [2]或list [3]等来查看特定段落。
到目前为止,我已经尝试了以下过程:
input = open("input.txt", "r") #Reading the input file
lines = input.readlines() #Creating a List with separate sentences
str = '' #Declaring a empty string
for i in range(len(lines)):
if len(lines[i]) > 2: #If the length of a line is < 2, It means it can be a new paragraph
str += lines[i]
此方法不会将段落存储到新列表中(因为我不确定该怎么做)。 它将只删除带有“ \\ n”的行,并将所有输入行存储到str变量中。 当我尝试显示str的内容时,它将输出显示为单词。 但是我需要它们作为句子。
而且我的代码应该将所有句子存储到第一次出现'\\ n'到单独的列表中,依此类推。
有什么想法吗?
更新我找到了一种打印直到'\\ n'为止存在的所有行的方法。 但是,当我尝试将它们存储到列表中时,它是作为字母而不是整个句子存储的。 以下是供参考的代码段
input = open("input.txt", "r")
lines = input.readlines()
input_ = []
for i in range(len(lines)):
if len(lines[i]) <= 2:
for j in range(i):
input_.append(lines[j]) #This line is storing as letters.
甚至“ input_ + =行”也存储为字母,而不是句子。
任何想法如何修改此代码以获得所需的输出?
不要忘记做input.close()
,否则文件将不会保存。
或者您可以使用with
。
#Using "with" closes the file automatically, so you don't need to write file.close()
with open("input.txt","r") as file:
file_ = file.read().split("\n")
现在, file_
是一个列表,其中每个段落都作为单独的项。
只需两行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.