我得到了這本詞典表示數學多項式:Python的字典到列表(數學polynoms)
{'x1': 2, 'x0': 1, 'x3': 3}
我想將其轉換爲一個列表(但他們可以在隨機順序,或沒有任何成員) :
{'x1': 2, 'x0': 1, 'x3': 3}
到
[1,2,0,3]
我得到了這本詞典表示數學多項式:Python的字典到列表(數學polynoms)
{'x1': 2, 'x0': 1, 'x3': 3}
我想將其轉換爲一個列表(但他們可以在隨機順序,或沒有任何成員) :
{'x1': 2, 'x0': 1, 'x3': 3}
到
[1,2,0,3]
首先轉換鍵轉爲更有用的數字:
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
嘗試[x for x,y in dictionary.items().sort(key=lambda x,y: int(x[1:]))]
這將字典轉換爲元組列表,並按關鍵術語中'x'後面的數字對列表進行排序。並輸出按鍵排序的值。
如果我正確理解您的問題,請嘗試如下所示:
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()
雖然也許不是最有效的方法...
這是什麼邏輯? – styvane