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.
可以使用^{} 对列表中出现在
0s
之间的元素进行分组:详细信息
这里的
key
参数key = lambda x: x != 0
正在转换列表,以便将其分组为:请注意,
groupby
将相等的连续值分组。 因此,这个键将产生以下值作为groupby
的结果:现在我们只需要指定如果
key
不是0
,我们希望保留values
,这可以通过在列表末尾添加if k != 0
来完成。你知道吗帮助阅读:
Python有一个惊人的特性,我们可以用它来实现所谓的切片。 我认为这种方法比其他使用itertools.groupby组. 你知道吗
代码:
结果:
使用列表理解代替地图内置函数的替代方法:
说明:
zip()函数接受iterables(如:list、string、dict)或用户定义的iterables,并基于iterable对象返回元组迭代器。你知道吗
map()函数有两个参数,第一个参数是函数名,第二个参数是序列(例如列表)seq。你知道吗
map()将函数应用于序列的所有元素。你知道吗
我们在这里使用它将list内置函数应用于zip函数的所有元组结果。你知道吗
借助于切片,我们为zip函数提供两个从列表中生成的iterables,一个从第一项开始,增量为2,另一个从第二项开始,增量也设置为2。你知道吗
解释此处使用的切片: l[::2]
切片教程:
link
python zip函数文档:
link
python映射函数文档:
link
python列表理解文档:
link
相关问题 更多 >
编程相关推荐