提问人:Patstro 提问时间:4/21/2023 最后编辑:wjandreaPatstro 更新时间:4/21/2023 访问量:109
尝试向嵌套列表中的数字添加值时遇到“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
问:
我目前正在尝试编写一个将采用嵌套列表的代码,请参见下文:
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]]
,然后执行以下操作:
- 跳过嵌套列表序列中的第一个和最后一个列表。
- 跳过列表 2 到 5 中大于 1 的第一个和最后一个值。(在上面的例子中,它是数字 4 和 5)。
- 在列表 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
答:
-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)
评论
example_list[j]
sub_list[j]
j
sub_list
example_list
round((example_list[j] + x), 3)
这就是问题所在。 是一个子列表,因此是一个错误。不能向列表添加整数。example_list[j]
example_list[j] + x