如果将数字除以连续的零个数,则将Python分成多个子列表

时间:2019-10-15 10:58:58

标签: python python-3.x algorithm list

嗨,我有以下列表:

l = [1,2,4,6,0,5,0,0,0,6,17,0,0,7,0]

我想要一个列表列表,其中每个子列表可以由索引或数字本身组成,拆分的条件是至少存在2个连续的0。
结果如下:

[[1,2,4,6,0,5],[6,17],[7,0]] # instead of the elements could be the indices  

你有什么解决办法吗?

2 个答案:

答案 0 :(得分:2)

这是使用itertools.groupby

的一种方法

例如:

from itertools import groupby

l = [1,2,4,6,0,5,0,0,0,6,7,0,0,7,0]
result = [[]]
for k, v in groupby(l):
    v = list(v)
    if k == 0 and len(v) > 1:
        result.append([])
    else:
        result[-1].extend(v)
print(result)

输出:

[[1, 2, 4, 6, 0, 5], [6, 7], [7, 0]]

答案 1 :(得分:0)

如果只有一位数字(感谢@ 3nomis),并且您不介意在字符串之间进行转换,则不必担心:

从列表中创建一个字符串:

l_str = ''.join(map(str, l))
  

'124605000670070'

以正则表达式分隔:

splits = re.split('0[0]+', l_str)
  

['124605','67','70']

再次加入映射回整数:

from functools import partial
result = map(partial(map, int), splits)
  

[[1、2、4、6、0、5],[6、7],[7、0]]

或作为一行(不建议使用):

map(partial(map, int), re.split('0[0]+', ''.join(map(str, l))))