如何在python3.x中执行for loop函数并输出sum?

2024-07-04 07:50:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个作业需要使用一个“for”语句来计算两个数据集的曼哈顿距离和欧几里得距离。我还需要定义数据集并按代码所示压缩它们。我对Python非常陌生,如果有关于如何打印abs(x-y)函数之和的提示,我将不胜感激!在

我希望输出显示为“曼哈顿距离:22.5”

这是我尝试过的

UserXRatings = [1,5,1,3.5,4,4,3]
UserYRatings = [5,1,5,1,1,1,1]    

for x, y in zip(UserXRatings, UserYRatings):
   print("Manhattan distance: ", abs(x-y))

Tags: 数据函数代码in距离for作业abs
2条回答

你很接近。您要做的是每次通过循环打印abs(x-y)的值。在循环过程中,您可能应该存储这些值的总和,然后在最后打印一次:

Python 3.3.3 (v3.3.3:c3896275c0f6, Nov 18 2013, 21:19:30) [MSC v.1600 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> UserXRatings = [1,5,1,3.5,4,4,3]
>>> UserYRatings = [5,1,5,1,1,1,1]
>>>
>>> z = 0  # Initialize the variable to store the running total.
>>> for x, y in zip(UserXRatings, UserYRatings):
...     z = z + abs(x-y)  # Calculate the running total of `abs(x-y)`.
...
>>> print("Manhattan distance: ", z)
Manhattan distance: 22.5
>>>

你可以用sum得到想要的结果-

print("Manhattan distance: ",sum(abs(x-y) for x,y in zip(UserXRatings, UserYRatings)))
#It should print - Manhattan distance:  22.5

相关问题 更多 >

    热门问题