![](/img/trans.png)
[英]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.