我有這樣的清單。
list = ['As Michael Harvey writes, paragraphs are “in essence—a form of punctuation, and like other former. ',
'',
'Many novice writers tend to make a sharp distinction between content and style, thinking that a paper can be strong']
正如我們可以觀察到的那樣,有一個空串列''。我想根據空串列拆分我的串列。
預期輸出:
#輸入
input list=['some text ', '', 'some texts example']
輸出:
list1= ['some text ']
list2= ['some text example']
uj5u.com熱心網友回復:
遍歷串列中的每個元素,當存在長度為 0 的元素時將其洗掉。
l = ['As Michael Harvey writes, paragraphs are “in essence—a form of punctuation, and like other former. ',
'',
'Many novice writers tend to make a sharp distinction between content and style, thinking that a paper can be strong']
output = [ele for ele in l if len(ele) > 0]
list1, list2 = output
這適用于您的示例,但它不會在空元素上“拆分”。然后你可以使用 for 回圈:
output = ['']
for ele in l:
if len(ele) > 0:
output[-1] = ele
else:
output.append('')
最后一部分拆分您的串列:
l = ['a', 'b', '', 'c']
output = ['']
for ele in l:
if len(ele) > 0:
output[-1] = ele
else:
output.append('')
# output = ['ab', 'c']
編輯:輸出為串列:
l = ['a', 'b', '', 'c']
output = [[]]
for ele in l:
if len(ele) > 0:
output[-1].append(ele)
else:
output.append([])
# output = [['a', 'b'], ['c']]
如果您有更多串列,它會在此處停止,因為輸出可以隨心所欲。如果你知道結果是兩個串列,你可以解壓它們:
lst1, lst2 = output
旁注:不要使用變數list,因為它是 python 中的資料結構。
uj5u.com熱心網友回復:
超級基本的解決方案。允許拆分兩個以上的句子。以句子變數的形式輸出,串列串列。
list = ['a','','b','','c']
sentences = []
for s in list:
if len(s)!=0:
sentences.append([s])
這里的其他答案中有更好更快的解決方案,這個只是詳細說明了一個不太技術/初學者友好的解決方案。
uj5u.com熱心網友回復:
如果您知道您將擁有多少個串列:
list1, *list2 = (i for i in input_list if i)
否則,如果您不知道最終會得到多少個串列,您可能會得到 adict或 a listoflist的
uj5u.com熱心網友回復:
您可以使用串列字典。
l = ['As Michael Harvey writes, paragraphs are “in essence—a form of punctuation, and like other former. ',
'',
'Many novice writers tend to make a sharp distinction between content and style, thinking that a paper can be strong']
lists = dict()
x = 1
for ele in l:
if(len(ele) > 0): # checking if the length of the element in l is sufficient (larger than 0)
lists[x] = [ele] # adding a list with the element to the dictionary
x = 1
輸出:
串列[1] = ['正如邁克爾·哈維所寫,段落“本質上是一種標點符號,和其他前者一樣。']
lists[2] = ['許多新手作家傾向于在內容和風格之間做出尖銳的區分,認為一篇論文可以很強大']
uj5u.com熱心網友回復:
如果您需要串列串列,可以使用此解決方案,并以 '' 作為分隔符:

在這里運行代碼
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/414400.html
標籤:
下一篇:將資料框轉換為列出并洗掉NaN值
