列表>列表清单

时间:2010-07-12 20:13:40

标签: python

在python中,无论我遇到什么地方,如何将长列表拆分为列表列表' - '。例如,我该如何转换:

['1', 'a', 'b','---', '2','c','d','---','3','123','e','---','4']

[['1', 'a', 'b'],['2','c','d'],['3','123','e'],['4']]

非常感谢提前。

6 个答案:

答案 0 :(得分:17)

In [17]: import itertools
# putter around 22 times
In [39]: l=['1', 'a', 'b','---', '2','c','d','---','3','123','e','---','4']

In [40]: [list(g) for k,g in itertools.groupby(l,'---'.__ne__) if k]
Out[40]: [['1', 'a', 'b'], ['2', 'c', 'd'], ['3', '123', 'e'], ['4']]

答案 1 :(得分:4)

import itertools

l = ['1', 'a', 'b','---', '2','c','d','---','3','123','e','---','4']
r = []

i = iter(l)
while True:
  a = [x for x in itertools.takewhile(lambda x: x != '---', i)]
  if not a:
    break
  r.append(a)
print r

# [['1', 'a', 'b'], ['2', 'c', 'd'], ['3', '123', 'e'], ['4']]

答案 2 :(得分:1)

import itertools

a = ['1', 'a', 'b','---', '2','c','d','---','3','123','e','---','4']
b = [list(x[1]) for x in itertools.groupby(a, '---'.__eq__) if not x[0]]

print b     # or print(b) in Python 3

结果是

[['1', 'a', 'b'], ['2', 'c', 'd'], ['3', '123', 'e'], ['4']]

答案 3 :(得分:1)

这是一种方法:

lst=['1', 'a', 'b','---', '2','c','d','---','3','123','e','---','4']
indices=[-1]+[i for i,x in enumerate(lst) if x=='---']+[len(lst)]
answer=[lst[indices[i-1]+1:indices[i]] for i in xrange(1,len(indices))]
print answer

基本上,这会在列表中找到字符串'---'的位置,然后相应地对列表进行切片。

答案 4 :(得分:0)

这是一个没有itertools的解决方案:

def foo(input):
    output = []
    currentGroup = []
    for value in input:
        if '-' in value:  #if we should break on this element 
            currentGroup.append( value )
        elif currentGroup:
            output.append( currentGroup )
            currentGroup = []
    if currentGroup:
        output.append(currentGroup) #appends the rest if not followed by separator    
    return output

print ( foo ( ['1', 'a', 'b','---', '2','c','d','---','3','123','e','---','4'] ) )

答案 5 :(得分:-1)

我已经有一段时间了,因为我已经完成了任何python,所以我的语法会有所不同,但是一个简单的循环就足够了。

以两个数字跟踪索引

firstList = ['1', 'a', 'b','---', '2','c','d','---','3','123','e','---','4']
listIndex = 0
itemIndex = 0
ii = 0
foreach item in firstList
  if(firstList[ii] == '---') 
    listIndex = listIndex + 1
    itemIndex = 0
    ii = ii + 1
  else secondList[listIndex][itemIndex] = firstList[ii]