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

时间:2018-12-04 20:45:14

标签: python python-2.7 list

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

所以说我有

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

并想返回:

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

有人可以帮忙吗? 谢谢!

2 个答案:

答案 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。这是有意的-您可以使用它来验证ab是此代码段的有效输入。

答案 1 :(得分:1)

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']