for k, pip in enumerate(tmp):
pip = round(pip, 4)
if pip in levels:
print str(pip) + ' is already in list!'
levels[pip] = (levels[pip] + int(round(percentiles[k]))) / 2.
else:
levels[pip] = int(round(percentiles[k]))
点数最多为4位小数,例如1.2345。级别是OrderDict
if
永远不会评估为真;始终分配(和覆盖)值。那我该如何处理钥匙?
另外,有更多的pythonic方法吗?我不能用percentiles
以某种方式压缩tmp
吗?
答案 0 :(得分:1)
>>> import collections
>>> d = collections.OrderedDict()
>>> d[1] = 2
>>> d
OrderedDict([(1, 2)])
>>> d[1.234] = 4
>>> d
OrderedDict([(1, 2), (1.234, 4)])
>>> d[1.234]
4
>>> d[round(1.2343, 3)]
4
是的,OrderedDict
可以将浮点数作为键。您看到的问题是由于其他原因 - 您希望在此循环之前填充levels
吗?或者你应该在循环中有多个值来舍入相同的值吗?
我快速修改了你的代码来测试它,一切顺利。你能提供一些导致你看到的错误的数据吗?
>>> cache = collections.OrderedDict()
>>> for index, value in enumerate([1.234, 2.345, 1.234]):
... rounded_value = round(value, 2)
... if rounded_value in cache:
... print("we already found {0}!".format(rounded_value))
... else:
... print("{0} is new".format(rounded_value))
... cache[rounded_value] = index
...
1.23 is new
2.35 is new
we already found 1.23!
答案 1 :(得分:0)
可能你正在寻找这个:
from odict import odict
levels=odict()
tmp=[1.01234,1.13333,1.233333,1.13333]
percentiles=[3.2,1,3,3]
for k, pip in enumerate(tmp):
pip = round(pip, 4)
if pip in levels:
print str(pip) + ' is already in list!'
#import pdb;pdb.set_trace()
levels[pip] = (levels[pip] + int(round(percentiles[k]))) / 2.
else:
levels[pip] = int(round(percentiles[k]))