簡體   English   中英

Python中的列表理解錯誤

[英]List Comprehension error in Python

我正在編寫一個代碼,其中需要使用綜合列表以使用x軸值的輸入來計算y軸值。 我有兩個問題。 首先,我需要弄清楚如何使用輸入列表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)

並在列表推導中使用這些值:

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

當我運行它時,它說:類型錯誤:'str'對象不可調用

我的第二個問題是a,b和c也都輸入了,我也必須能夠將它們放在其中,但無法弄清楚如何輸入。

任何幫助或建議,不勝感激。

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]

像這樣?

Python不像您和我那樣理解數學語法。 您需要明確指定要執行的所有數學運算。

a(x**2)

並不是說“一次(x等於2的冪)”,而是“調用方法'a',其中'x等於2的冪”)。您想這樣做:

a * x**2

請注意,指數運算符的優先級高於乘法,因此不需要括號。

同樣,您不能寫“ bx”,但需要寫b * x。

似乎“ 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是字符串類型; 您不能像這樣的“ a(x ** 2)”倍數,它是python中的調用函數; 改成 :

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