[英]Python Newbie: Calculating with two lists one of it a 2d list
是的,首先我是 Python 新手。 我的任務是編寫類似的、更簡單的層次分析過程 (ahp) 變體。 我不允許帶任何像 numpy 這樣的包裹。
我需要一個列表輸入 [n*m] 像:
liste = [[1.0,2.0,3.0],[4.0,5.0,6.0],[7.0,8.0,9.0]]
我已經意識到它是這樣的:
liste = input("Put in the Matrix: ")
我需要總結列:
col_sums = [ sum(x) for x in zip(*liste) ]
現在它需要計算歸一化列表,它看起來像這樣:
liste = [[1.0,2.0,3.0],
[4.0,5.0,6.0],
[7.0,8.0,9.0]]
list_norm = 1.0/col_sums[0] 2.0/col_sums[1] ...
4.0/col_sums[0] 5.0/col_sums[1] ...
7.0/col_sums[0] 8.0/col_sums[1] ...
實現它的正確方法是什么?
感謝您的反饋和關注。
到目前為止,您做其他所有事情的方式看起來都是正確的。 您只需要對list_norm
另一個列表理解:
liste = [[1.0,2.0,3.0],
[4.0,5.0,6.0],
[7.0,8.0,9.0]]
col_sums = [ sum(x) for x in zip(*liste) ]
list_norm = [[e / col_sums[c] for c, e in enumerate(row)] for row in liste]
# [[0.083, 0.133, 0.166],
# [0.333, 0.333, 0.333],
# [0.583, 0.533, 0.5]]
我們在這里使用enumerate()
獲取元素及其列表索引,並使用索引從col_sums
獲取適當的總和。
正如@kaya3 在評論中提到的,替代的、更清潔的解決方案:
list_norm = [[e / s for e, s in zip(row, col_sums)] for row in liste]
其中zip()
從它的兩個參數生成相應的元素對。 從功能上講,這是相同的代碼片段,並產生相同的結果。
沒有任何特別干凈的方法可以將整個過程放在一行中,但我認為沒有必要這樣做。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.