编写一个Python代码,用它们的平方值替换下面列表中的所有整数,包括子列表中的整数



我想对这个列表中的值进行平方,但我一直得到[1,3,[0,10],8,9,[13]]作为我的输出。

这是我的代码:

new_list = [1,3, [0,10], 8, 9, [13]]
for i in range(len(new_list)):
if type(new_list[i]) == int:
new_list[i] == (new_list[i] ** 2)
else:
nested_list1 = new_list[2]
nested_list2 = new_list[5]
for i in range(len(nested_list1)):
nested_list1[i] == (nested_list1[i] ** 2)
for i in range(len(nested_list2)):
nested_list2[i] == (nested_list2[i] ** 2)
print(new_list)

您的代码中有拼写错误。你有==,你的意思是=

此外,您的代码不断对嵌套列表进行平方运算的次数超过实际次数。

你本想写这个代码:

new_list = [1, 3, [0, 10], 8, 9, [13]]
for i in range(len(new_list)):
if type(new_list[i]) == int:
new_list[i] = (new_list[i] ** 2)
else:
nested_list = new_list[i]
for i in range(len(nested_list)):
nested_list[i] = (nested_list[i] ** 2)
print(new_list)

输出:

[1, 9, [0, 100], 64, 81, [169]]

最新更新