2016-04-10 77 views
-3

我得到了這本詞典表示數學多項式:Python的字典到列表(數學polynoms)

{'x1': 2, 'x0': 1, 'x3': 3} 

我想將其轉換爲一個列表(但他們可以在隨機順序,或沒有任何成員) :

{'x1': 2, 'x0': 1, 'x3': 3} 

[1,2,0,3] 
+2

這是什麼邏輯? – styvane

回答

0

首先轉換鍵轉爲更有用的數字:

poly_dict = {int(term[1:]): power for term, power in poly_dict.items()} 

這是假設每學期與x所以它可以只是割掉的第一個字符被刪除開始,即term[1:]

然後找到最大功率:

max_power = max(poly_dict.keys()) 

初始化權力的列表,默認爲0,但對於每學期細胞:

poly_list = [0] * (max_power + 1) 

然後填寫它:

for term, power in poly_dict.items(): 
    poly_list[term] = power 
0

你想要的字典作爲列表的值?你可以簡單地存檔這與

d = {'x1': 2, 'x0': 1, 'x3': 3} 
values = list(d.values()) 

因此,值將是[2,1,3]。零成員是什麼意思?

+0

零成員是「x2」:0,這是不是在字典 – LukinM26

+0

@ LukinM26所以這解決了你的問題? – Querenker

0

嘗試[x for x,y in dictionary.items().sort(key=lambda x,y: int(x[1:]))] 這將字典轉換爲元組列表,並按關鍵術語中'x'後面的數字對列表進行排序。並輸出按鍵排序的值。

0

如果我正確理解您的問題,請嘗試如下所示:

MAX_ORDER = 20 
p = [] 
for i in range(MAX_ORDER+1) : 
    try: 
     p += [d['n'+str(i)]] 
    except: 
     p += [0] 
while not p[-1]: 
    p.pop() 

雖然也許不是最有效的方法...