简体   繁体   中英

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. I have two questions. First, I need to figure out how to use the values in my input list 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

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.

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. 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:

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.

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.

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; you can not multiple like this "a(x**2)", it is a calling function in python; change to :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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