尝试向嵌套列表中的数字添加值时遇到“TypeError:只能将列表(而不是”int“)连接到列表”错误

Running into a 'TypeError: can only concatenate list (not "int") to list' error when attempting to add values to numbers in nested lists

提问人:Patstro 提问时间:4/21/2023 最后编辑:wjandreaPatstro 更新时间:4/21/2023 访问量:109

问:

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

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 加 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)

但是我遇到了一个错误。我假设这是因为我试图在我的列表值中添加一个数字 1,但我似乎无法弄清楚如何解决它并让我的代码做我想要的事情。TypeError: can only concatenate list (not "int") to list

python-3.x 嵌套列表 枚举

评论

0赞 wjandrea 4/21/2023
看起来应该是(两次),因为是 的索引,而不是 .我投票结束这个问题,因为这似乎基本上是一个错别字。查看如何询问,了解未来问题的提示,例如制作一个最小的可重现示例,仅包含足够的代码来重现问题和所需的输出。另请参阅 Eric Lippert 的 How to debug 小程序example_list[j]sub_list[j]jsub_listexample_list
0赞 John Gordon 4/21/2023
round((example_list[j] + x), 3)这就是问题所在。 是一个子列表,因此是一个错误。不能向列表添加整数。example_list[j]example_list[j] + x

答:

-1赞 911 4/21/2023 #1
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)

评论

0赞 Community 4/24/2023
您的答案可以通过其他支持信息进行改进。请编辑以添加更多详细信息,例如引文或文档,以便其他人可以确认您的答案是正确的。您可以在帮助中心找到有关如何写出好答案的更多信息。