如何解决python根据分隔符创建子列表
我有一个清单
sentence = ['1','00','and','4','2','3']
我正在尝试找到一种方法来创建基于分隔符“和”的子列表列表。所以每个子列表只能有一个“和”。而额外的 and 只是作为列表的元素保留,而不是放在 sublit 中。
sentence = [['1','4'],['2','3']]
我试过了
sentence = ['1','3']
nbAnd = 0
temp=[]
for i,j in enumerate(sentence):
t= []
if j.isdigit():
t.append(j)
if j == "and":
nbAnd +=1
if nbAnd<1:
t.append(j)
else:
temp.append(j)
nbAnd=0
temp.append(t)
print(temp)
这就是我得到的:
[['1'],['00'],[],['4'],['2'],['3']]
预计到达时间: “and”之前的数字必须始终在“and”之后有一个更大的“len”。 所以
['1','3','five','six']
应该是:
[['1','3'],'six']
感谢您的帮助。
解决方法
您需要遍历 sentence
列表并保留一个 temp
变量来检查有多少 and
。如果有超过 1 个 and
,只需在 temp
变量中添加任何内容。
output = []
temp = []
for i in sentence:
if i=='and':
if 'and' in temp:
output.append(temp.copy())
output.append(i)
temp.clear()
else:
temp.append(i)
else:
temp.append(i)
output.append(temp.copy())
print(output)
[['1','00','and','4'],['2','3']]
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。