简体   繁体   English

如何在Python 3.x中执行循环功能并输出总和?

[英]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.

相关问题 如何从带参数构建的 3.x 运行 python 2.x 函数? PSS/E - How can i run a python 2.x function from a 3.x built with arguments? PSS/E 我可以在python 3.x中的函数内动态切换函数吗? - Can I dynamically switch functions inside of a function in python 3.x? 如何在Python 3.x中将未知参数应用于函数? - How do I apply unknown arguments to a function in Python 3.x? 如何在 python 3.x 中打印格式化数组? - How can I print a formatted array in python 3.x? 如何在Python 3.x中验证日期? - How can I validate a date in Python 3.x? 如何在 Python 3.x 中逐行打印网页 - How can I print a webpage line by line in Python 3.x 如何在 Python 3.x 中检查字符串中的新行? - How can I check for a new line in string in Python 3.x? Python 3.x-使用sum函数连接列表中的字符串 - Python 3.x - Using the sum function to concatenate strings in a list 如何在每次 [Python 3.x] 的不同输出的同一行(shell 或窗口)中重新打印 2D 数组或多个输出? - How can I reprint 2D array or multiple outputs in the same line of (shell or window) with different output each time [Python 3.x]? 如何使用python 3.x执行多项式加法和乘法? - How to perform polynomial addition and multiplication using python 3.x?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM