您可以编写一个简单的函数来迭代列表,以将每个元素增加n
像这样:
def increment_by_n(lst, n):
for i in range(len(lst)):
for j in range(len(lst[i])):
lst[i][j] += n
return lst
关于第4行的解释:lst[i][j] += n
,让我们探讨以下内容:
for i in range(len(lst)): # line 2
# the above means : for i in [0, 1, 2]
# because len(lst) = 3 and hence range(3) = [0, 1, 2]
# we use this to reference lst[i], i.e lst[0] = [8, 9], lst[1] = [5, 7]
# Note that lst[0][0] = 8, we will use this below!
for j in range(len(lst[i])): # line 3
# first, len(lst[0]) = len(lst[8, 9]) = 2
# range(2) = [0, 1]
# so the above means: for j in [0, 1]
lst[i][j] += n # Line 4
# We are here referencing the i in [0, 1, 2] and j in [0, 1] in order
# lst[0][0] = 8 and hence, 8 + 1 = 9
# lst[0][1] = 9 and hence, 9 + 1 = 10
# lst[1][0] = 5 and hence, 5 + 1 = 6, and so on...
Note这将修改您的初始列表。