我试图将我的 list 拆分为 sublists,条件是元素 '|'
中的任何内容都将被视为新 sublist 的元素。我忽略了任何带有空字符串的元素,因此这些元素不会包含在最终的 list 中。我有以下 list:
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])
回答1
@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']]
这也适用于 list 中的字符串由多个字符组成的情况。 list 中的最后一个元素隐含地依赖于“|”。
回答2
一种可能的解决方案:
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']]
回答3
除非您真的需要某些东西的索引,否则在 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
有空子lists:
[[], ['a', 'b', 'c'], [], ['d', 'e'], []]
您可以使用简单的 list 理解过滤掉它:
[l for l in nlist if len(l) != 0]
输出
[['a', 'b', 'c'], ['d', 'e']]
回答4
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)
另一种方式