从Lis生成子列表

2024-05-20 00:55:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我想把一个列表分成一个子列表。例如

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

应该导致

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

我的第一个想法是获取'Met'的所有索引,构建类似元组[(0, 4), (5, 8), (9, 11)]的范围,然后对列表进行切片。但那好像是用大锤敲碎了一个螺母。。你知道吗


Tags: 列表切片serprosplit元组met螺母
3条回答

请尝试以下列表:

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

输出(在w):

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

您可以使用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)]

输出:

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

下面是一个使用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, []))

输出:

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

相关问题 更多 >