尝试向嵌套列表中的数字添加值时遇到“TypeError: can only concatenate list (not "int") to list”错误

问题描述 投票:0回答:1

我目前正在尝试编写一个将采用嵌套列表的代码,见下文:

example_list = [[ 0, 4, 5, 0, 0, 0, 0], 
                [ 4, 2, 3, 5, 0, 0, 0], 
                [ 0, 4, 2, 3, 5, 0, 0], 
                [ 4, 2, 3, 5, 0, 0, 0], 
                [ 0, 4, 2, 3, 5, 0, 0], 
                [ 0, 4, 5, 0, 0, 0, 0]]

并执行以下操作:

  1. 跳过嵌套列表序列中的第一个和最后一个列表。
  2. 跳过列表 2 到 5 中第一个和最后一个大于 1 的值。(在上面的示例中,它将是数字 4 和 5)。
  3. 在列表 2-5 中第一个和最后一个大于 1 的值之间加 1。

在其他人的帮助下,我尝试了以下代码:

x = 1

for i, sub_list in enumerate(example_list[1:-1], start=1):
    for j, entry in enumerate(sub_list[1:-1][1:-1], start=2):
        if j > 1:
            example_list[j] = round((example_list[j] + x), 3)
        example_list[i][j] += 1
print(example_list)

但是我遇到了一个

TypeError: can only concatenate list (not "int") to list
错误。我假设这是因为我正在尝试将数字 1 添加到我的列表值中,但我似乎无法弄清楚如何解决它并让我的代码执行我想要的操作。

python python-3.x nested-lists enumerate
1个回答
0
投票
x = 1
for i, sub_list in enumerate(example_list[2:5], start=2):
    for j, entry in enumerate(sub_list[2:-2], start=2):
        if entry > 1 and j != 2 and j != len(sub_list) - 2:
            example_list[i][j] += 1
print(example_list)
© www.soinside.com 2019 - 2024. All rights reserved.