3 回答
TA贡献2039条经验 获得超7个赞
使用列表理解,您可以这样做:
x_squared = [item_x**2 for item_x in x]
y_cubed = [item_y**3 for item_y in y]
TA贡献1921条经验 获得超9个赞
您只是附加了最后一个结果。如果你想坚持你所涵盖的主题,你应该使用for循环:
x = [2,4,6,8,10,12,14,16,18]
y = [10,8.25,7.5,7,6.5,7,7.5,8.25,10]
xsquared = []
ycubed = []
for item_X in x:
xsquared.append(item_X ** 2)
for item_Y in y:
ycubed.append(item_Y ** 3)
但是,最简单的方法是使用列表推导式:
x = [2,4,6,8,10,12,14,16,18]
y = [10,8.25,7.5,7,6.5,7,7.5,8.25,10]
xsquared = [n ** 2 for n in x]
ycubed = [n ** 3 for n in x]
两种情况下的输出:
print(xsquared)
print(ycubed)
[4, 16, 36, 64, 100, 144, 196, 256, 324]
[1000, 561.515625, 421.875, 343, 274.625, 343, 421.875, 561.515625, 1000]
TA贡献1860条经验 获得超9个赞
如果你想避免列表理解或 map()
x = [2,4,6,8,10,12,14,16,18]
y = [10,8.25,7.5,7,6.5,7,7.5,8.25,10]
x2 = []
y3 = []
for i in x:
x2.append(i*i)
for i in y:
y3.append(i**3)
添加回答
举报