如何在列表中拆分列表?

时间:2015-06-22 21:45:05

标签: python

如果我有一个如下列表:

a = [0.0, 0.968792, 1.0, 0.904219, 0.920049, 1.0, 0.738674, 0.760266, 1.0]

我想:

a = [[0.0, 0.968792, 1.0], [0.904219, 0.920049, 1.0], [ 0.738674, 0.760266, 1.0]]

3 个答案:

答案 0 :(得分:1)

a = [0.0, 0.968792, 1.0, 0.904219, 0.920049, 1.0, 0.738674, 0.760266, 1.0]
l = [[]]

for ind,ele in enumerate(a):
    if ele == 1:
        l[-1].append(ele)
        if ind < len(a)-1:
            l.append([])
    else:
        l[-1].append(ele)
print(l)
[[0.0, 0.968792, 1.0], [0.904219, 0.920049, 1.0], [0.738674, 0.760266, 1.0]]

适用于任何有1:

的地方
a = [0.0, 0.968792, 1.0,1.0, 0.904219, 1.0,0.920049, 1.0, 0.738674, 0.760266, 1.0]
l = [[]]

for ind, ele in enumerate(a):
    if ele == 1:
        l[-1].append(ele)
        if ind < len(a)-1:
            l.append([])
    else:
        l[-1].append(ele)
print(l)

[0.0, 0.968792, 1.0], [1.0], [0.904219, 1.0], [0.920049, 1.0], [0.738674, 0.760266, 1.0]]

如果你正在做很多这样的工作,你可以使用numpy:

a = [0.0, 0.968792, 1.0, 1.0, 0.904219, 1.0, 0.920049, 1.0, 0.738674, 0.760266, 1.0]
import numpy as np
x = np.array(a)
print np.split(x, np.where(x == 1)[0] + 1)

答案 1 :(得分:0)

这应该完成你的任务。请参阅代码中的注释以获得进一步说明:

#!/usr/bin/env python3
# coding: utf-8

# sample list
a = [0.0, 0.968792, 1.0, 0.904219, 0.920049, 1.0, 0.738674, 0.760266, 1.0]

# empty list to store sublists in
l = list()

# variable to store index (position) of found '1.0' in given list 'a'
last_idx = 0

# walk through list a, i represents the index of the element, e the element itself
for i, e in enumerate(a):
    # find elements equal to 1.0 and append a slice of the list a to the list l
    if e == 1.0:
        l.append(a[last_idx:i+1])
        last_idx = i+1

print(l)

输出为:

[[0.0, 0.968792, 1.0], [0.904219, 0.920049, 1.0], [0.738674, 0.760266, 1.0]]

可以在此处找到使用过的命令的文档:

答案 2 :(得分:0)

要拆分列表l,在值v之后,您需要在l中找到v的索引。 您可以使用lists index method查找第一个v的索引,并使用slicing在此索引后拆分列表l。以下功能将使用前面提到的。

def split_at(l, v):
    r = []
    while l:                             # while l is not empty
        try:                             # if v is in l
            ind = l.index(v) + 1
            r.append( l[:ind] )
            l = l[ind:]
        except:                          # if v is not in l
            r.append(l)
            l = []
    return r

一些证明正确性的例子:

>>> split_at([], 1)
[]

>>> split_at([1], 1)
[[1]]

>>> split_at([1,1,1,1,1], 1)
[[1], [1], [1], [1], [1]]

>>> split_at([1,2,1], 1)
[[1], [2, 1]]

>>> split_at([1,2,1,1], 1)
[[1], [2, 1], [1]]

>>> split_at([2,1,2], 1)
[[2, 1], [2]]

根据要求,空列表示例可能被视为不正确。