简体   繁体   中英

Generate Sublist from List

I wanna split a list into a list of sublists. Eg

amino = ['Met','Phe','Pro','Ala','Ser','Met','Ser','Gly','Gly','Met','Thr','Trp']

should result in

amino_split = [['Met','Phe','Pro','Ala','Ser'],['Met','Ser','Gly','Gly'],['Met','Thr','Trp']]

My first thought was to get all indices of 'Met' and build range-like tuples [(0, 4), (5, 8), (9, 11)] and then slice the list. But that seems like using a sledgehammer to crack a nut..

You can use itertools.groupby :

import itertools
amino = ['Met','Phe','Pro','Ala','Ser','Met','Ser','Gly','Gly','Met','Thr','Trp']
final_vals = [list(b) for _, b in itertools.groupby(amino, key=lambda x:x == 'Met')]
last_data = [final_vals[i]+final_vals[i+1] for i in range(0, len(final_vals), 2)]

Output:

[['Met', 'Phe', 'Pro', 'Ala', 'Ser'], ['Met', 'Ser', 'Gly', 'Gly'], ['Met', 'Thr', 'Trp']]

Try this list comprehension:

w = []
[w.append([]) or w[-1].append(e) if 'Met' in e else w[-1].append(e) for e in amino]

Output (in w ):

[['Met', 'Phe', 'Pro', 'Ala', 'Ser'],
 ['Met', 'Ser', 'Gly', 'Gly'],
 ['Met', 'Thr', 'Trp']]

Below is one solution using reduce.

import functools
amino = ['Met','Phe','Pro','Ala','Ser','Met','Ser','Gly','Gly','Met','Thr','Trp']
print(functools.reduce(lambda pre, cur: pre.append([cur]) or pre if cur == 'Met' else pre[-1].append(cur) or pre, amino, []))

Output:

[['Met', 'Phe', 'Pro', 'Ala', 'Ser'], ['Met', 'Ser', 'Gly', 'Gly'], ['Met', 'Thr', 'Trp']]
[Finished in 0.204s]

You can use Pandas:

import pandas as pd
amino = ['Met','Phe','Pro','Ala','Ser','Met','Ser','Gly','Gly','Met','Thr','Trp']
s = pd.Series(amino)
s.groupby(s.eq('Met').cumsum()).apply(list).tolist()

Output:

[['Met', 'Phe', 'Pro', 'Ala', 'Ser'],
 ['Met', 'Ser', 'Gly', 'Gly'],
 ['Met', 'Thr', 'Trp']]

If range is fixed then you can normally use splicing to achieve your goal. ex; [amino[:5],amino[5:9],amino[9:12]]

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