簡體   English   中英

如何獲取多維python列表的輸入

[英]how to take input for multidimentional python list

#this code take input of three equation like matrix and print them
eqn_no = int(raw_input("Enter Equation no: ->"))
eqn=[] #main variable to hold data like [[1,2,3],[4,5,6]]
co_eff=[] #secondary variable to temporarily hold data like[1,2]
x_val=[] #hold the last term of eqn like[3,6]
for i in range(eqn_no):
    for j in range(eqn_no):
         co_eff.append(float(raw_input("Enter Co eff of a%d %d term: " %((i+1),(j+1))))) #append co-efficients piece by piece
    x_val.append(float(raw_input("Enter Co eff of b%d term: " %((i+1))))) #append last term of the equation
    eqn.append(co_eff) #appends the the equation
for i in range(eqn_no):
    co_eff=eqn[i] #takes the i number equation's co-efficient
    for j in range(eqn_no):
        print co_eff[j]
    print x_val[i]

該代碼可以完美地輸入,但不能正確打印。 它僅顯示eqn [0],但輸出x_value OK。 無法找出問題所在。 我需要學習這樣的輸出,因為我必須訪問列表的值。 例如,如果兩個方程都像x + 2y = 3,4x + 5y = 6,那么我想像1 2 3 4 5 6一樣輸出,並且我還想要一種方法來逐個訪問eqn []的每一項(通過a環)。

這是一個非常簡單的正則表達式,它將使您開始從等式中獲取值:

>>> import re
>>> def getvalues(eqn):
    return [1 if digit == '' else int(digit) for digit in re.match(r'(\d*)x\+(\d*)y=(\d*)',eqn).groups()]

>>> getvalues('x+2y=3')
[1, 2, 3]
>>> getvalues('4x+5y=6')
[4, 5, 6]

這會將每次迭代的co_eff列表重置為該迭代等於eqn [i]的值:

for i in range(eqn_no):
    co_eff=eqn[i] #takes the i number equation's co-efficient
    for j in range(eqn_no):
        print co_eff[j]
    print x_val[i]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM