简体   繁体   English

从列表生成子列表

[英]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. 我的第一个想法是获取'Met'所有索引并构建类似范围的元组[(0, 4), (5, 8), (9, 11)] ,然后切片列表。 But that seems like using a sledgehammer to crack a nut.. 但这好像是用大锤敲开坚果。

You can use itertools.groupby : 您可以使用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 ): 输出(以w ):

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

Below is one solution using reduce. 以下是使用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]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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