按值拆分列表并保留分隔符

时间:2017-07-19 11:59:43

标签: python

我有一个名为list_of_strings的列表,如下所示:

['a', 'b', 'c', 'a', 'd', 'c', 'e']

我想将此列表拆分为一个值(在本例中为c)。我还想在结果分割中保留c

所以预期的结果是:

[['a', 'b', 'c'], ['a', 'd', 'c'], ['e']]]

这么简单吗?

8 个答案:

答案 0 :(得分:2)

您可以使用more_itertoools简单明了地完成此操作:

from more_itertools import split_after


lst = ["a", "b", "c", "a", "d", "c", "e"]
list(split_after(lst, lambda x: x == "c"))
# [['a', 'b', 'c'], ['a', 'd', 'c'], ['e']]

另一个例子,我们只需更改predicate

即可拆分单词
lst = ["ant", "bat", "cat", "asp", "dog", "carp", "eel"]
list(split_after(lst, lambda x: x.startswith("c")))
# [['ant', 'bat', 'cat'], ['asp', 'dog', 'carp'], ['eel']]

答案 1 :(得分:2)

您可以尝试以下内容:

list_of_strings = ['a', 'b', 'c', 'a', 'd', 'c', 'e']

output = [[]]

for x in list_of_strings:
    output[-1].append(x)
    if x == 'c':
        output.append([])

虽然应该注意,如果输入的最后一个元素是'c'

,这会在输出中附加一个空列表

答案 2 :(得分:1)

def spliter(value, array):
    res = []
    while value in array:
        index = array.index(value)
        res.append(array[:index + 1])
        array = array[index + 1:]
    if array:
        # Append last elements
        res.append(array)
    return res

a = ['a', 'b', 'c', 'a', 'd', 'c', 'e']
print(spliter('b',a))
# [['a', 'b'], ['c', 'a', 'd', 'c', 'e']]
print(spliter('c',a))
# [['a', 'b', 'c'], ['a', 'd', 'c'], ['e']]

答案 3 :(得分:1)

这个怎么样?它应该只迭代输入一次,其中一些是index方法,它作为本机代码执行。

def splitkeep(v, c):

    curr = 0
    try:
        nex = v.index(c)
        while True:
            yield v[curr: (nex + 1)]
            curr = nex + 1
            nex += v[curr:].index(c) + 1

    except ValueError:
        if v[curr:]: yield v[curr:]

print(list(splitkeep( ['a', 'b', 'c', 'a', 'd', 'c', 'e'], 'c')))

结果

[['a', 'b', 'c'], ['a', 'd', 'c'], ['e']]

如果最终值是您要拆分的值,我不确定您是否要在结果的末尾保留一个空列表。我做了一个假设,你不会,所以如果它是空的,我会排除最后一个值。

这导致输入[]仅导致[],可能会导致[[]]

答案 4 :(得分:0)

这个相当有趣的脚本怎么样:

a = ['a', 'b', 'c', 'a', 'd', 'c', 'e']

b = ''.join(a).split('c')  # ['ab', 'ad', 'e']

c = [x + 'c' if i < len(b)-1 else x for i, x in enumerate(b)]  # ['abc', 'adc', 'e']

d = [list(x) for x in c if x]
print(d)  # [['a', 'b', 'c'], ['a', 'd', 'c'], ['e']]

它还可以使用"c"

处理开头和结尾
a = ['c', 'a', 'b', 'c', 'a', 'd', 'c', 'e', 'c']
d -> [['c'], ['a', 'b', 'c'], ['a', 'd', 'c'], ['e', 'c']]

答案 5 :(得分:0)

list_of_strings = ['a', 'b', 'c', 'a', 'd', 'c', 'e']

value = 'c'
new_list = []
temp_list = []
for item in list_of_strings:
    if item is value:
        temp_list.append(item)
        new_list.append(temp_list[:])
        temp_list.clear()
    else:
        temp_list.append(item)

if (temp_list):
    new_list.append(temp_list)

print(new_list)

答案 6 :(得分:0)

stuff = ['a', 'b', 'c', 'a', 'd', 'c', 'e']

你可以像这样找到'c'的索引,然后加1,因为你会在它之后拆分,而不是在它的索引处:

indices = [i + 1 for i, x in enumerate(stuff) if x == 'c']

然后像这样提取切片:

split_stuff = [stuff[i:j] for i, j in zip([0] + indices, indices + [None])]

zip为您提供了类似于(indices[i], indices[i + 1])的元组列表,其中连接的[0]允许您提取第一部分,[None]提取最后一个切片({ {1}})

答案 7 :(得分:0)

您可以尝试使用以下代码段。使用more_itertools

>>> l = ['a', 'b', 'c', 'a', 'd', 'c', 'e']
>>> from more_itertools import sliced
>>> list(sliced(l,l.index('c')+1))

输出是:

[['a', 'b', 'c'], ['a', 'd', 'c'], ['e']]
相关问题