每次元素以特定的子字符串开头时,我都希望将列表切成子列表。
所以说我有
a = ['XYthe', 'cat' , 'went', 'XYto', 'sleep','XYtoday','ok']
b = 'XY'
并想返回:
a1 = ['XYthe', 'cat', 'went']
a2 = ['XYto', 'sleep']
a3 = ['XYtoday', 'ok']
有人可以帮忙吗? 谢谢!
答案 0 :(得分:3)
a = ['XYthe', 'cat' , 'went', 'XYto', 'sleep','XYtoday','ok']
b = 'XY'
final_list = []
for word in a:
if word.startswith(b): # if the word starts with 'XY'...
final_list.append([word]) # ...then make a new sublist
else:
final_list[-1].append(word) # otherwise, add the word to the last sublist so far
print(final_list)
# [['XYthe', 'cat', 'went'], ['XYto', 'sleep'], ['XYtoday', 'ok']]
如果a
的第一个元素不包含b
,则代码将引发一个IndexError
。这是有意的-您可以使用它来验证a
和b
是此代码段的有效输入。
答案 1 :(得分:1)
a = ['XYthe', 'cat' , 'went', 'XYto', 'sleep','XYtoday','ok']
b = 'XY'
# Use list comprehension
emp = []
[emp.append([i]) if i.startswith(b) else emp[-1].append(i) for i in a]
print(emp)
[['XYthe', 'cat', 'went'], ['XYto', 'sleep'], ['XYtoday', 'ok']]
print(emp[0])
['XYthe', 'cat', 'went']