[英]Can't figure out TypeError
I got a (TypeError: can't multiply sequence by non-int of type 'float') error and I can't figure out how to fix it. 我遇到了一个(TypeError:无法将序列乘以'float'类型的非整数)的错误,我不知道如何解决它。 I've searched the error and wasn't able to figure out how to fix it because the code examples that had the error didn't look like the code I'm having a problem with.
我已经搜索了该错误,但无法找出解决方法,因为出现错误的代码示例与我遇到问题的代码并不相似。
# Variable stuff
initialMagnitudes = input("What are the initial magnitudes of the
vector? (separate with spaces)\t").split()
for string in initialMagnitudes:
string = float(string)
initialDirections = input("What are the initial directions of the
vector? (in degrees and separate with spaces)\t").split()
for string in initialDirections:
string = float(string)
vector_i = []
vector_j = []
vectorEquation = "Xi + Yj"
resultantMagnitude = 0.0
resultantDirection = 0.0
resultantVectorEquation = "R = Xi + Yj"
def find_vector_equation():
global vectorEquation
global vector_i
global vector_j
for magnitude in initialMagnitudes:
theta =
float(initialDirections[initialMagnitudes.index(magnitude)])
vector_i.append(math.cos(math.radians(theta))*magnitude)
vector_j.append(math.sin(math.radians(theta))*magnitude)
vectorEquation = "{}i + {}j".format(vector_i, vector_j)
print("The resultant vector equation is: "+vectorEquation)
find_vector_equation()
Here is all the code that could be part of the problem. 这是可能是问题一部分的所有代码。 Thanks in advance for all the help!
在此先感谢您提供的所有帮助!
This is the problem: 这就是问题:
for string in initialMagnitudes:
string = float(string)
This doesn't change anything in initialMagnitudes
. 这不会改变
initialMagnitudes
任何initialMagnitudes
。 Instead, you change the variable string
to be a float version of its string value, and then throw away that float. 而是将变量
string
更改为其字符串值的浮点版本,然后丢弃该浮点。 The loop variable in a for
statement is a value, not a slot in the list; for
语句中的循环变量是一个值,而不是列表中的插槽。 it has no idea where it came from and assigning to it does not put the value back in the list. 它不知道它来自哪里,分配给它也不会将该值放回列表中。
Since the items of initialMagnitudes
are still strings, trying to multiply by one of them is trying to multiply a string by a float, and you get the error you get. 由于
initialMagnitudes
的项目仍然是字符串,因此尝试将它们乘以其中之一就是将字符串乘以浮点数,就会得到错误。
Best to do it with a list comprehension: 最好通过列表理解来做到这一点:
initialMagnitudes = [float(value) for value in initialMagnitudes]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.