我想通過一個十六進制字符的列表,進入一個lambda函數,減少計算一個總的十進制值。我不知道我在做什麼錯,但Python解釋器將不能識別列表(枚舉(逆轉(numList))元組的列表。Python:從列表到枚舉列表傳遞給lambda reduce函數
numList = ['3', '0', 'e', 'f', 'e', '1']
reduce(lambda sum,(up,x):sum+ int(x,16)*16**up,
enumerate(reversed(numList)))
當我打印出來
list(enumerate(reversed(numList))
這是一個元組列表
[(0, '1'), (1, 'e'), (2, 'f'), (3, 'e'), (4, '0'), (5, '3')]
但它吐了錯誤:只能串聯元組(而不是「INT」),以元組
UPDATE:
的代碼現在與未成年人除了」 0" 的工作加入到拉姆達
reduce(lambda sum,(up,x):sum+ int(x,16)*16**up,
list(enumerate(reversed(numList))),0)
我不明白是什麼意思。另外我不確定什麼是最好的方法來解決這個問題。
that means you make sure, that it starts with 0 instead of the first Argument - in this case (0,'1') - because otherwise the types dont match? – am2 1 min ago
。
the third argument you add is initializer. without it, the sum in first iteration will be (0,'1'). so you were trying to evaluate (0,'1')+int(x,16)*16**up which is invalid. – ymonad 14 mins ago
更新2:
reduce(lambda sum,(up,x):sum+ int(x,16)*16**up,enumerate(reversed(numList)),0)
是一樣的好,enumerate()
回報ITER和list(enumerate...)
是多餘的。
標記爲已解決。
第三你添加的參數是初始值設定項。沒有它,第一次迭代中的'sum'將是'(0,'1')'。所以你試圖評估無效的'(0,'1')+ int(x,16)* 16 ** up'。 https://docs.python.org/2/library/functions.html#reduce – ymonad
啊好的。該消息是說我正在嘗試將int添加到元組中。 (我在想另一種方式。)我現在明白了,謝謝。 – theMobDog
這意味着你要確保它以0開頭而不是第一個參數 - 在這種情況下(0,'1') - 因爲否則類型不匹配? – am2