Python:以固定长度移动列表中的元素 [英] Python: shift elements in a list with constant length

查看:171
本文介绍了Python:以固定长度移动列表中的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种编写简单函数的优雅方法,该函数将list的元素移动给定数量的位置,同时保持列表的长度相同,并使用默认值填充空位置.这将是函数的文档字符串:

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 !

推荐答案

我将使用切片分配:

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:以固定长度移动列表中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆