将整数列表拆分为给定0的子列表作为sep

2024-04-26 14:24:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个整数列表:

l = [6, 6, 0, 5, 4, 5, 0, 0, 4, 6]

我必须通过使用连续的零作为分隔符拆分上面的列表来生成以下列表,以便得到:

res = [[6, 6], [5, 4, 5] , [4, 6]]

Tags: 列表res整数分隔符
2条回答

可以使用^{}对列表中出现在0s之间的元素进行分组:

from itertools import groupby
[list(v) for k,v in groupby(l, key = lambda x: x != 0) if k != 0]
# [[6, 6], [5, 4, 5], [4, 6]]

详细信息

这里的key参数key = lambda x: x != 0正在转换列表,以便将其分组为:

[x != 0 for x in l]
# [True, True, False, True, True, True, False, False, True, True]

请注意,groupby将相等的连续值分组。 因此,这个键将产生以下值作为groupby的结果:

[list(v) for k,v in groupby(l, key = lambda x: x != 0)]
[[6, 6], [0], [5, 4, 5], [0, 0], [4, 6]]

现在我们只需要指定如果key不是0,我们希望保留values,这可以通过在列表末尾添加if k != 0来完成。你知道吗


帮助阅读:

Python有一个惊人的特性,我们可以用它来实现所谓的切片。 我认为这种方法比其他使用itertools.groupby组. 你知道吗

代码:

l = [6, 6, 0, 5, 4, 5, 0, 0, 4, 6]
res = list(map(list, zip(l[::2], l[1::2])))
print(res)

结果:

[(6, 6), (0, 5), (4, 5), (0, 0), (4, 6)]

使用列表理解代替地图内置函数的替代方法:

res = [list(i) for i in (zip(l[::2], l[1::2]))] 

说明:

zip()函数接受iterables(如:list、string、dict)或用户定义的iterables,并基于iterable对象返回元组迭代器。你知道吗

map()函数有两个参数,第一个参数是函数名,第二个参数是序列(例如列表)seq。你知道吗

map()将函数应用于序列的所有元素。你知道吗

我们在这里使用它将list内置函数应用于zip函数的所有元组结果。你知道吗

借助于切片,我们为zip函数提供两个从列表中生成的iterables,一个从第一项开始,增量为2,另一个从第二项开始,增量也设置为2。你知道吗

解释此处使用的切片: l[::2]

Lists have a default bit of functionality when slicing. If there is no value before the first colon, it means to start at the beginning index of the list. If there isn't a value after the first colon, it means to go all the way to the end of the list. That last colon tells Python that we'd like to choose our slicing increment. By default, Python sets this increment to 1, but that extra colon at the end of the numbers allows us to specify what we want it to be.

切片教程:

link

python zip函数文档:

link

python映射函数文档:

link

python列表理解文档:

link

相关问题 更多 >