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

How to modulo through list and move its contents

模如何与列表一起使用?

此函数 returns 新分布 q,向右移动 U 个单位。如果U = 0q应该和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小时,

You can think of all hours in history wrapping around a circle of 24 hours over and over and the current hour of the day is that infinitely long number mod 24. It is a much more profound concept than just a remainder, it is a mathematical way to deal with cycles and it is very important in computer science. It is also used to wrap around arrays, allowing you to increase the index and use the modulus to wrap back to the beginning after you reach the end of the array.

取模对列表不起作用,取模只影响索引值U。U在这里用于将列表一分为二:

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

modulo 对你的作用是确保 U 保持在 0 和 len(p)-1 之间,没有它你可以为 U 输入一个非常大的值并得到索引错误。

另请注意,在您的代码中,行

q = []

不执行任何操作,因为在步骤中再次创建了 q:

q = p[-U:] + p[:-U]
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))

如果您需要对某一部分进行进一步解释,请告诉我