[英]How can I perform a function for loop and output a sum in Python 3.x?
I have an assignment that requires using a single "for" statement to calculate the manhattan and euclidian distances of two data sets. 我有一个作业,需要使用一个“ for”语句来计算两个数据集的曼哈顿距离和欧氏距离。 I'm also required to define the data sets and zip them as shown in the code.
我还需要定义数据集并压缩它们,如代码所示。 I'm very new to Python, and any tips on how to print the sum of the abs(xy) function would be greatly appreciated!
我对Python还是很陌生,关于如何打印abs(xy)函数之和的任何提示将不胜感激!
I'd like the output to read "Manhattan Distance: 22.5" 我希望输出内容为“曼哈顿距离:22.5”
Here is what I've tried 这是我尝试过的
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))
You can use sum to get desired result- 您可以使用sum来获得预期的结果-
print("Manhattan distance: ",sum(abs(x-y) for x,y in zip(UserXRatings, UserYRatings)))
#It should print - Manhattan distance: 22.5
You're close. 你近了 What you're doing is printing the value of
abs(xy)
each time through the loop. 您正在做的是每次循环都打印
abs(xy)
的值。 You should probably store the sum of the values as you go through the loop, then print it once at the end: 遍历循环时,您可能应该存储值的总和,然后在末尾打印一次:
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
>>>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.