首页 > 解决方案 > Python:将列表切成子列表,每次元素都以特定的子字符串开头

问题描述

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

所以说我有:

a = ['XYthe', 'cat' , 'went', 'XYto', 'sleep','XYtoday','ok']
b = 'XY'

并想返回:

a1 = ['XYthe', 'cat', 'went']
a2 = ['XYto', 'sleep']
a3 = ['XYtoday', 'ok']

谁能帮忙?谢谢!

标签: pythonpython-2.7list

解决方案


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是此代码片段的有效输入。


推荐阅读