2 回答
TA贡献1799条经验 获得超6个赞
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))
如果您需要对某一部分做进一步的解释,请告诉我
TA贡献1804条经验 获得超3个赞
Modulo 不适用于列表,modulo 仅影响索引值 U。 U 用于将列表一分为二:
p[-U:] + p[:-U]
modulo 对您的作用是确保 U 保持在 0 和 len(p)-1 之间,如果没有它,您可能会为 U 输入一个非常大的值并得到一个索引错误。
还要注意,在您的代码中,该行
q = []
在步骤中再次创建 q 时什么都不做:
q = p[-U:] + p[:-U]
添加回答
举报