概述
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:以固定长度移动列表中的元素所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复