简体   繁体   English

根据特定字符串将列表拆分为子列表

[英]Split a list into sublists based on certain string

I am pretty new to python, so my question is:我对python很陌生,所以我的问题是:

I have a list like this:我有一个这样的清单:

L = ['Name1', 'String1', 'String2', 'String3', 'Name2', 'String4', 'String5', 'String6', ...]

I would like to convert it into a new list in which all the strings after a certain 'name' are in a sub-list with the name like:我想将它转换成一个新列表,其中某个“名称”之后的所有字符串都在一个子列表中,名称如下:

L2 = [['Name1', 'String1', 'String2', 'String3'],['Name2', 'String4', 'String5', 'String6'],[...]]

Whats the best way to do that?最好的方法是什么?

Let's assume that there is a function isname() that tells us whether an element of list L is a name:让我们假设有一个函数 isname() 告诉我们列表 L 的元素是否是一个名称:

Lsub = []
L2 = []
for e in L:
    if isname(e):
        if Lsub: 
            L2.append(Lsub)
        Lsub = [e]
    else:
        Lsub.append(e)
L2.append(Lsub)

Perhaps not the most Pythonic, but:也许不是最 Pythonic 的,但是:

import re

L = ['Name1', 'String1', 'String2', 'String3', 'Name2', 'String4', 'String5', 'String6']

l_temp = re.split(r'(Name\d+)', ' '.join(L))

new_L = [[item] + l_temp[i+1].strip().split(' ') 
        for i, item in enumerate(l_temp) if item.startswith('Name')]

print new_L

"Flat is better than nested", but "simple is better than complex" and "readability counts" , so... “扁平优于嵌套”,但“简单优于复杂”和“可读性很重要” ,所以......

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

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