我是靠谱客的博主 舒适铃铛,这篇文章主要介绍python列表中元素移动,Python:以固定长度移动列表中的元素,现在分享给大家,希望可以做个参考。

I'm looking for an elegant way to write a simple function that would shift the elements of list by a given number of positions, while keeping the list of the same length and padding empty positions with a default value. This would be the docstring of the function:

def shift_list(l, shift, empty=0):

"""

Shifts the elements of a list **l** of **shift** positions,

padding new items with **empty**::

>>> l = [0, 1, 4, 5, 7, 0]

>>> shift_list(l, 3)

[0, 0, 0, 0, 1, 4]

>>> shift_list(l, -3)

[5, 7, 0, 0, 0, 0]

>>> shift_list(l, -8)

[0, 0, 0, 0, 0, 0]

"""

pass

How would you proceed ? Any help greatly appreciated !

解决方案

I'd use slice assignment:

def shift_list(l, shift, empty=0):

src_index = max(-shift, 0)

dst_index = max(shift, 0)

length = max(len(l) - abs(shift), 0)

new_l = [empty] * len(l)

new_l[dst_index:dst_index + length] = l[src_index:src_index + length]

return new_l

最后

以上就是舒适铃铛最近收集整理的关于python列表中元素移动,Python:以固定长度移动列表中的元素的全部内容,更多相关python列表中元素移动,Python:以固定长度移动列表中内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(50)

评论列表共有 0 条评论

立即
投稿
返回
顶部