如何对列表取模并移动其内容

时间:2019-03-29 10:32:02

标签: python list modulo

列表如何取模?

此函数返回新的分布q,向右移动U个单位。如果为U = 0,则q应该与p相同。

p = [0, 1, 0, 0, 0]

def move(p, U):
    U = U % len(p)
    q = p[-U:] + p[:-U]
    return q

print(move(p, 1))

代码输出正确:[0, 0, 1, 0, 0]

如何用外行的术语描述此python代码的数学步骤?

已解决

为了更好地理解Modulo的工作原理,我编写了以下代码并检查了输出: for i in range(40): print('the number : ', i) print('number % 5 : ', i%5)

余数是余数,而不仅仅是余数。另一个用户以这种鼓舞人心的方式表达了这一观点:

一天24小时的思考,

  

您可以想到历史上的所有小时都围绕24小时一圈地循环,而一天中的当前小时就是无限长的mod24。这是一个比余数更深刻的概念,它是一种处理周期的数学方法,在计算机科学中非常重要。它也用于环绕数组,允许您增加索引并使用模数在到达数组末尾后返回到开头。

2 个答案:

答案 0 :(得分:0)

Modulo不适用于列表,modulo仅影响索引值U。U用于在此处将列表一分为二:

 public function update(User $user, Broadcast $broadcast)
{

    if($this->isAdmin($user)){
        foreach($broadcast as $broadcasts) {
            if($broadcasts->pivot->organization_specific === 'true') {
                return true;
            }
        }
    }
    return false;
}

取模为您做的是确保U保持在0到len(p)-1之间,否则,您可以为U输入一个非常大的值并得到索引错误。

还要在您的代码中注意行

p[-U:] + p[:-U]

什么都不做,因为在该步骤中再次创建了q:

q = []

答案 1 :(得分:0)

p=[0, 1, 0, 0, 0] # asign a list to the variable p

def move(p, U): # define a new function. Its name is 'move'. It has 2 parameters p and U
    q = [] # Assign an empty list to the variable q
    # len(p) returns the size of the list. In your case: 5
    # You calculate the remainder of U / len(p) ( this is what modulo does)
    # The remainder is assigned to U
    U = U % len(p)
    # p[-U:] gets U items from the list and beginning from the end of the lis
    # e.g. [1,2,3][-2:] --> [2,3]
    # the second part returns the other side of the list.
    # e.g. [1,2,3][:-2] --> [1]
    # These two lists are concatenated to one list, assigned to q
    q = p[-U:] + p[:-U]
    # The new list is returned
    return q

print(move(p, 1))

让我知道您是否需要对某一部分进行进一步的解释