'|'我試圖根據元素中的任何內容都將被視為新子串列的元素的條件將我的串列拆分為子串列。我忽略了任何帶有空字串的元素,因此這些元素不會包含在最終串列中。我有以下串列:
slist = ['|', 'a', 'b', 'c', '|', '', '|', 'd', 'e', '|']
結果將是:
[['a', 'b', 'c'], ['d', 'e']]
我已經撰寫了以下代碼,有人可以告訴我如何解決這個問題:
start = 0; end = 0
nlist = []
for s in range(0, len(slist)-1):
ns = s 1
if slist[s] == '|' and ns == '|':
end = s - 1
elif slist[s] == '|':
start = s 1
nlist.append(nlist[start:end])
uj5u.com熱心網友回復:
@simre 提倡的拆分/連接技術適用于問題中顯示的資料。這是一種基于回圈的方法,可能更靈活:
slist = ['|', 'a', 'b', 'c', '|', '', '|', 'd', 'e', '|']
result = []
e = []
for v in slist:
if v == '|':
if e:
result.append(e)
e = []
elif v:
e.append(v)
print(result)
輸出:
[['a', 'b', 'c'], ['d', 'e']]
這也適用于串列中的字串由多個字符組成的情況。隱含依賴串列中的最后一個元素等于“|”。
uj5u.com熱心網友回復:
一種可能的解決方案:
slist = ['|', 'a', 'b', 'c', '|', '', '|', 'd', 'e', '|']
inList = False
res = []
subl = []
for e in slist:
if not inList and e == '|':
# Only to find the start.
inList = True
elif inList:
if e == '|':
if len(subl) > 0:
# Append only if subl is not empty
res.append(subl)
subl = []
elif e:
# Append only non empty elements
subl.append(e)
資源:
[['a', 'b', 'c'], ['d', 'e']]
uj5u.com熱心網友回復:
除非你真的需要某些東西的索引,否則在 Python 中你應該直接回圈遍歷元素。然后只需要幾個if-s 來決定如何處理當前元素:
slist = ['|', 'a', 'b', 'c', '|', '', '|', 'd', 'e', '|']
nlist = [[]]
for x in slist:
if x != "": # ignore empty
if x == "|":
nlist.append([]) # add a new sub-list
else:
nlist[-1].append(x) # or append the element to the current one
此時nlist有空子串列:
[[], ['a', 'b', 'c'], [], ['d', 'e'], []]
您可以通過簡單的串列理解將其過濾掉:
[l for l in nlist if len(l) != 0]
輸出
[['a', 'b', 'c'], ['d', 'e']]
uj5u.com熱心網友回復:
slist = ['|', 'a', 'b', 'c', '|', '', '|', 'd', 'e', '|']
relevant =[ i for i , x in enumerate(slist) if x =='|']
i=0
new=[[]]
while(len(slist)>0 and i!=len(relevant)):
x=slist[relevant[i] 1:relevant[i 1]]
new[0].append(x)
i=i 2
print(new)
其他方式
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/474778.html
