29

如果我们在 python 中有一个listofstrings并且想要基于一些特殊的创建子列表string我们应该怎么做?

例如:

l = ["data","more data","","data 2","more data 2","danger","","date3","lll"]
p = split_special(l,"")

会产生:

p = [["data","more data"],["data 2","more data 2","danger"],["date3","lll"]]
4

6 回答 6

35

itertools.groupby是一种方法(通常是这样):

>>> l = ["data","more data","","data 2","more data 2","danger","","date3","lll"]
>>> from itertools import groupby
>>> groupby(l, lambda x: x == "")
<itertools.groupby object at 0x9ce06bc>
>>> [list(group) for k, group in groupby(l, lambda x: x == "") if not k]
[['data', 'more data'], ['data 2', 'more data 2', 'danger'], ['date3', 'lll']]

由于这种特殊情况,我们甚至可以作弊:

>>> [list(group) for k, group in groupby(l, bool) if k]
[['data', 'more data'], ['data 2', 'more data 2', 'danger'], ['date3', 'lll']]
于 2013-01-25T20:11:21.497 回答
5

使用 itertools 的一种可能实现

>>> l
['data', 'more data', '', 'data 2', 'more data 2', 'danger', '', 'date3', 'lll']
>>> it_l = iter(l)
>>> from itertools import takewhile, dropwhile
>>> [[e] + list(takewhile(lambda e: e != "", it_l)) for e in it_l if e != ""]
[['data', 'more data'], ['data 2', 'more data 2', 'danger'], ['date3', 'lll']]

注意*

这和使用 groupby 一样快

>>> stmt_dsm = """
[list(group) for k, group in groupby(l, lambda x: x == "") if not k]
"""
>>> stmt_ab = """
it_l = iter(l)
[[e] + list(takewhile(lambda e: e != "", it_l)) for e in it_l if e != ""]
"""
>>> t_ab = timeit.Timer(stmt = stmt_ab, setup = "from __main__ import l, dropwhile, takewhile")
>>> t_dsm = timeit.Timer(stmt = stmt_dsm, setup = "from __main__ import l, groupby")
>>> t_ab.timeit(100000)
1.6863486541265047
>>> t_dsm.timeit(100000)
1.5298066765462863
>>> t_ab.timeit(100000)
1.735611326163962
>>> 
于 2013-01-25T20:35:46.753 回答
2

reduce想到:

def split(iterable, where):
    def splitter(acc, item, where=where):
        if item == where:
            acc.append([])
        else:
            acc[-1].append(item)
        return acc
    return reduce(splitter, iterable, [[]])


data = ["data","more data","","data 2","more data 2","danger","","date3","lll"]
print split(data, '')

结果:

[['data', 'more data'], ['data 2', 'more data 2', 'danger'], ['date3', 'lll']]
于 2013-01-25T20:35:53.607 回答
1

我不确定这是否是最“pythonic”的解决方法。

def split_seq(seq, sep):
    start = 0
    while start < len(seq):
        try:
           stop = start + seq[start:].index(sep)
           yield seq[start:stop]
           start = stop + 1
        except ValueError:
           yield seq[start:]
           break

ll = ["data","more data","","data 2","more data 2","danger","","date3","lll"]
p = [i for i in split_seq(ll,"")]
于 2013-01-25T20:05:19.700 回答
0

这是一个想法。:)

def spec_split(seq,sep):
    # Ideally this separator will never be in your list
    odd_sep = "!@#$%^&*()"

    # Join all the items with the odd separator and split
    # anywhere the odd separator + separator + odd seperator meet
    # This makes a list of items broken by the separator
    jumble = odd_sep.join(seq).split(odd_sep+sep+odd_sep)

    # split the remaining items broken by odd separators into sublists
    return [item.split(odd_sep) for item in jumble] 
于 2013-01-25T20:48:51.567 回答
0
    lst = ["data","more data","","data 2","more data 2","danger","","date3","lll"]
    join_list = ",".join(lst)
    split_list = join_list.split(",,")
    result = [i.split() for i in split_list]
    #result =[['data,more', 'data'], ['data', '2,more', 'data', '2,danger'],  ['date3,lll']]
于 2019-07-09T05:49:13.300 回答