简体   繁体   English

Python中的列表理解错误

[英]List Comprehension error in Python

I'm working on a code in which in need to use a comprehensive list to calculate the y-axis values, using the input of x-axis values. 我正在编写一个代码,其中需要使用综合列表以使用x轴值的输入来计算y轴值。 I have two questions. 我有两个问题。 First, I need to figure out how to use the values in my input list xx: 首先,我需要弄清楚如何使用输入列表xx中的值:

 print("How many x-axis values do you have?")
 xv = input("-->")
 print("What are your x-axis values? Put in each value and press enter.")
 xx = []
 while len(xx) < int(xv):
  item = float(input("-->"))
  xx.append(item)

and use those values inside the list comprehension: 并在列表推导中使用这些值:

y = [(a(x**2))+ bx + c) for x in xx]

When I run this, it says: Type error: 'str' object is not callable 当我运行它时,它说:类型错误:'str'对象不可调用

My second question is that a,b, and c are also input, and i need to be able to put them in there too, but can't figure out how. 我的第二个问题是a,b和c也都输入了,我也必须能够将它们放在其中,但无法弄清楚如何输入。

Any help or advice is appreciated. 任何帮助或建议,不胜感激。

print("How many x-axis values do you have?")
xv = input("-->")
print("What are your x-axis values? Put in each value and press enter.")
xx = []
while len(xx) < int(xv):
    item = float(input("-->"))
    xx.append(item)
a=float(input("a?:"))
b=float(input("b?:"))
c=float(input("c?:"))
y = [(a*(x**2)+ b*x + c) for x in xx]

Like this? 像这样?

Python doesn't understand mathematical syntax in the same way you and I do. Python不像您和我那样理解数学语法。 You need to explicitly specify all mathematical operations you perform. 您需要明确指定要执行的所有数学运算。

a(x**2)

Doesn't mean "a times (x to the power of 2)", but rather "invoke the method 'a' with 'x to the power of 2' as the argument). You want to do this instead: 并不是说“一次(x等于2的幂)”,而是“调用方法'a',其中'x等于2的幂”)。您想这样做:

a * x**2

Note that the exponential operator has precedence over multiplication so there is no need for the parenthesis. 请注意,指数运算符的优先级高于乘法,因此不需要括号。

Similarily, you can't write 'bx' but you need to write b * x. 同样,您不能写“ bx”,但需要写b * x。

It also seems that 'a' is a string so you need to convert it to an int or a float before using it in mathematical expressions. 似乎“ a”是一个字符串,因此您需要在数学表达式中使用它之前将其转换为int或float。

print("How many x-axis values do you have?")
xv = input("-->")
print("What are your x-axis values? Put in each value and press enter.")
xx = []
while len(xx) < int(xv):
 item = float(input("-->"))
 xx.append(item)
a, b, c = map(float, (a, b, c))
y = [(a * x**2 + b * x + c) for x in xx]

如Joshua所述,问题的第二部分需要a * x ** 2 + b * x + c,我不确定您要问的是什么,但我想您想要的是:

    a,b,c = eval(input("Please input a,b and c separated by a comma: "))                  
y = [(a(x**2)+ bx + c) for x in xx]

var a is a string type; var a是字符串类型; you can not multiple like this "a(x**2)", it is a calling function in python; 您不能像这样的“ a(x ** 2)”倍数,它是python中的调用函数; change to : 改成 :

y = [(a*(x**2)+ b*x + c) for x in xx]

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

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