Python 列表>;名单
在python中,我如何在遇到“-”时将一个长列表拆分为一个列表列表。例如,如何转换:Python 列表>;名单,python,Python,在python中,我如何在遇到“-”时将一个长列表拆分为一个列表列表。例如,如何转换: ['1', 'a', 'b','---', '2','c','d','---','3','123','e','---','4'] 到 非常感谢。我已经有一段时间没有使用任何python了,所以我的语法可能会有偏差,但是一个简单的循环就足够了 import itertools l = ['1', 'a', 'b','---', '2','c','d','---','3','123','e','---','4
['1', 'a', 'b','---', '2','c','d','---','3','123','e','---','4']
到
非常感谢。我已经有一段时间没有使用任何python了,所以我的语法可能会有偏差,但是一个简单的循环就足够了
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']]
以两个数字跟踪索引
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]
结果是
[['1', 'a', 'b'], ['2', 'c', 'd'], ['3', '123', 'e'], ['4']]
这里有一个没有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'] ) )
这里有一种方法:
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
基本上,这会在列表中找到字符串“--”的位置,然后相应地对列表进行切片。+1由于采用了高效的
iter
方法(只使用一次),我更喜欢这个方法,而不是我的类似解决方案(很快就会删除它)。但是你可能想用替换范围(7)
中的j的,而True
来处理任意长度。+1很好(没有立即想到itertools.groupby
,但它确实符合要求)谢谢你的回答。是否有方法使用正则表达式(类似于x==re.match('-'))检查上行中的x=='-'?非常感谢,如果不是k,您可以在itertools.groupby(l,lambda x:re.match('--',x))中使用类似于[list(g)for k,g]的内容。当x
与模式不匹配时,表达式re.match(…)
返回None。因此,对于要保留的元素,k
是None
。因此,我将条件更改为如果不是k
。您可以使用'-'。\uu___
而不是lambda函数超过某个阈值,可读性是相对的。在我看来,这就像是一大堆代码。使用(1)value.find('-')==-1而不是value
(2)camelCase(2)冗余括号(el)if
有时(3)括号内的多余空格有时(4)足够长的语句插入ferschlugginer水平滚动条(5)逗号后面没有空格有时会让我觉得它像一堆乱七八糟的代码。
[['1', 'a', 'b'], ['2', 'c', 'd'], ['3', '123', 'e'], ['4']]
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'] ) )
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