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

取模如何处理列表?


此函数返回一个新的分布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 小时的圆圈里一遍又一遍地环绕着一天中的当前小时是无限长的数字 mod 24。这是一个比余数更深刻的概念,它是一种数学方法处理循环,这在计算机科学中非常重要。它还用于环绕数组,允许您增加索引并在到达数组末尾后使用模数回绕到开头。


拉丁的传说
浏览 197回答 2
2回答

哈士奇WWW

p=[0, 1, 0, 0, 0] # asign a list to the variable pdef 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 qprint(move(p, 1))如果您需要对某一部分做进一步的解释,请告诉我

狐的传说

Modulo 不适用于列表,modulo 仅影响索引值 U。 U 用于将列表一分为二:p[-U:] + p[:-U]modulo 对您的作用是确保 U 保持在 0 和 len(p)-1 之间,如果没有它,您可能会为 U 输入一个非常大的值并得到一个索引错误。还要注意,在您的代码中,该行q = []在步骤中再次创建 q 时什么都不做:q = p[-U:] + p[:-U]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python