[英]Python: Slice list into sublists, every time element begins with specific substring
I want to slice list into sublists, every time element begins with specific substring.我想将列表切成子列表,每次元素都以特定的子字符串开头。
So say I have:所以说我有:
a = ['XYthe', 'cat' , 'went', 'XYto', 'sleep','XYtoday','ok']
b = 'XY'
And want to return:并想返回:
a1 = ['XYthe', 'cat', 'went']
a2 = ['XYto', 'sleep']
a3 = ['XYtoday', 'ok']
can anyone help?有人可以帮忙吗? Thank you!
谢谢!
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']]
If the first element of a
doesn't contain b
, the code will raise an IndexError
.如果第一个元素
a
不包含b
,代码将引发IndexError
。 This is intentional - you could use it to validate that a
and b
are valid inputs to this snippet of code.这是有意的 - 您可以使用它来验证
a
和b
是否是此代码片段的有效输入。
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']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.