2 回答

TA貢獻1799條經(jīng)驗 獲得超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條經(jīng)驗 獲得超3個贊
Modulo 不適用于列表,modulo 僅影響索引值 U。 U 用于將列表一分為二:
p[-U:] + p[:-U]
modulo 對您的作用是確保 U 保持在 0 和 len(p)-1 之間,如果沒有它,您可能會為 U 輸入一個非常大的值并得到一個索引錯誤。
還要注意,在您的代碼中,該行
q = []
在步驟中再次創(chuàng)建 q 時什么都不做:
q = p[-U:] + p[:-U]
添加回答
舉報