python - 分组元素后跟列表中的重复键
问题描述
如何将元素分组到以 Pythonlst
开头的子列表中?'S'
lst = ['S', 'one', 'two', 'S', 'three', 'S', 'four', 'five', 'six']
我想要的是:
[['S', 'one', 'two'], ['S', 'three'], ['S', 'four', 'five', 'six']]
编辑:
如果现在lst = ['"A"', 'one', 'two', '"B"', 'three', '"C"', 'four', 'five', 'six']
呢?第一个元素并不完全相同,但有一些共同点,即引号。
解决方案
使用简单的迭代。
前任:
lst = ['S', 'one', 'two', 'S', 'three', 'S', 'four', 'five', 'six']
res = []
for i in lst:
if i =="S":
res.append([i])
else:
res[-1].append(i)
print(res)
输出:
[['S', 'one', 'two'], ['S', 'three'], ['S', 'four', 'five', 'six']]
问题已编辑。
使用str.startswith
&str.endswith
前任:
lst = ['"A"', 'one', 'two', '"B"', 'three', '"C"', 'four', 'five', 'six']
res = []
for i in lst:
if i.startswith('"') and i.endswith('"'):
res.append([i])
else:
res[-1].append(i)
print(res)
# --> [['"A"', 'one', 'two'], ['"B"', 'three'], ['"C"', 'four', 'five', 'six']]