简体   繁体   English

Python:将列表切成子列表,每次元素都以特定的子字符串开头

[英]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.这是有意的 - 您可以使用它来验证ab是否是此代码片段的有效输入。

Use list comprehension with if/else:列表理解if/else 结合使用:

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.

相关问题 每次出现元素时,将列表分为子列表,从特定子字符串开始 - Split list into sublists at every occurrence of element starting with specific substring 每次在子列表列表中切换数字时计数 [python 3] - count every time a number switches in a list of sublists [python 3] Python:检查列表中的每个元素是否存在特定时间 - Python: check if every element in a list exists a specific time 一行python代码可返回特定列中包含特定子字符串的列表的所有子列表 - One line python code to return all sublists of list containing specific substring in a particluar column 蟒蛇。 分割一部分以特定字符开头和以字符结尾的字符串 - Python. slice a part of the string that begins with a specific character and end with a character Python根据子列表中的第一个元素将列表拆分为子列表 - Python Split list into sublists based on the first element in the sublists 在 Python 中对列表中的每个字符串进行切片 - Slice every string in list in Python Python列表列表->使元素n成为子列表 - Python list of lists -> make sublists of element n 当列表以特定元素开头并以特定元素结尾时,python 中的列表切片列表? - Slice lists of list in python when list starts with specific element and end with specific element? 反转 Python 中列表的特定切片 - Reverse a specific slice of a list in Python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM