繁体   English   中英

我如何使用字符串获取和平均形成python?

[英]How could I get and average form python using strings?

我正在尝试使用以下代码得出平均值:

average = print(please, please2,please3/3)
print(average)

但是这个错误出现了

Traceback (most recent call last):
  File "C:\Users\Philip\Desktop\Python Stuff\Python Task.py", line 31, in <module>
    average = print(please, please2,please3/3)
TypeError: unsupported operand type(s) for /: 'str' and 'int'

而且我不知道这意味着什么,无论我尝试什么,都无法平均使用字符串please, please2, please3

您尝试在此处将字符串除以整数:

please3/3

其中please3是代码中的字符串值:

>>> '10'/3
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for /: 'str' and 'int'

您必须先将值转换为数字,我在这里选择了int()

>>> please3 = '10'
>>> please3 / 3
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for /: 'str' and 'int'
>>> int(please3) / 3
3.3333333333333335

所有这些都不能给您一个平均值,因为对于平均值,您需要首先对三个值求和

(int(please) + int(please2) + int(please3)) / 3

它会更好,如果你尽早作出从字符串到整数这个转换,也许你正在阅读从文件信息,此时你也想转换成字符串存在

您的问题是Python语言使用一种称为键入的计算概念。

假设您有3个苹果,5个橙子和4个叉子。 如果我告诉您将它们加在一起并给我您有多少水果,则您必须在脑海中查看每个对象,确定是否为水果,然后“转换”以评估是否为水果。您应该将它们添加到总计中。 有些是可兑换的(例如桔子和苹果),而有些则不能通过大量工作兑换(例如叉子)。

在这种情况下,即使您将这些变量读为“ 10”,“ 5”和“ 3”,编译器也不知道它们是整数(缩写为“ int”)并将它们视为“字符串”(缩写为'STR')。 您需要先将它们“类型转换”为整数,然后编译器才知道如何执行“ /”。

在这种情况下,您可以使用Python函数'int'来实现。

(int(please) + int(please2) + int(please3)) / 3

(您无需在末尾转换3,因为它已被识别为int。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM