简体   繁体   中英

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 . This is intentional - you could use it to validate that a and b are valid inputs to this snippet of code.

Use list comprehension with 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']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM