就像是新手一样,所以请忍受我。
我正在尝试将嵌套列表的每个元素加1
简单明了的列表很有效:
a = [1,2,3,4,5,6,7,8]
for i in range(len(a)):
a[i] += 1
但是为什么不起作用:
a = [[1, 2], [3, 4], [5, 6], [7, 8]]
我想念什么?
答案 0 :(得分:1)
让我们展开循环,以便我们进行检查:
a = [1, 2, 3, 4, 5, 6, 7, 8]
i = 0
assert a[i] == 1 # the zeroeth element of a
a[i] += 1 # increment 1, making it 2
assert a[i] == 2
i = 1
# ... etc, repeat
与
对比a = [[1, 2], [3, 4], [5, 6], [7, 8]]
i = 0
assert a[i] == [1, 2] # the zeroeth element of a is now the list [1, 2]!
a[i] += 1 # TypeError! What's the logical equivalent of adding 1 to a list? There isn't one
答案 1 :(得分:0)
a = [[1, 2], [3, 4], [5, 6], [7, 8]]
列表中的每个项目又是一个列表。您需要分别遍历和增加每个对象。因此,nested for loop
可以解决您的问题。
### Using recursion - The level of nesting doesn't matter
def incrementor(arr):
for i in range(len(arr)):
if type(arr[i]) is list:
incrementor(arr[i])
else:
arr[i] = arr[i] + 1
a = [[1, 2], [3, 4], [5, 6], [7, 8],9,10,11,12,[13,[14,15,16]],[[17,18],[19,[20,21]]]]
incrementor(a)
print(a)
[[2,3],[4,5],[6,7],[8,9],10,11,12,13,[14,[15,16,17]],[[ 18,19],[20,[21,22]]]]
答案 2 :(得分:0)
在第一次迭代中,您的a[i] += 1
实际上是a[0] = [1, 2] + 1
。那完全没有道理。您需要第二个内部循环。
使用嵌套的循环:
for i in range(len(a)):
for ii in range(len(a[i])):
a[i][ii] += 1
答案 3 :(得分:0)
因为您拥有嵌套列表,所以您必须再次迭代嵌套的列表
这是一种很酷的方法来检查是否有递归列表
a = [1,[2, 4],3,[4, 5],5,6,7,8]
def increment_a_list(some_list):
for i in range(len(some_list)):
if type(some_list[i]) is list: # if the element is a list then execute the function again with that element
increment_a_list(some_list[i])
else:
some_list[i] += 1 # +1 to that element if it not a list
return some_list
print(increment_a_list(a))
答案 4 :(得分:0)
当列表a或嵌套列表中还有另一个列表时,它将不起作用。因此,您需要嵌套循环: 以下程序会有所帮助:
a = [[1, 2], [3, 4], [5, 6], [7, 8]]
for i in range(len(a)):
for j in range(len(a[i])):
a[i][j] += 1
希望对您有帮助!