我正在尝试将十六进制字符列表传递到 lambda 函数中,并减少计算总十进制值。我不确定我做错了什么,但 python 解释器不会将 list(enumerate(reversed(numList)) 识别为元组列表。
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”)连接到元组
更新:
代码现在可以在 lambda 中添加少量“,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...)
是多余的。
将其标记为已解决。
最佳答案
当您真正需要的是计算总和时,您不需要使用通用的 reduce
函数。
这有效并且简单得多:
sum( int(x,16)*16**up for up,x in enumerate(reversed(numList)) )
<小时/>
另外,我猜你已经知道你可以做同样的事情,如下所示:
int(''.join(numList), 16)
关于Python:从列表到枚举列表以传递给 lambda reduce 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40169608/