在Python字典中匹配一个实数键

2024-09-27 22:20:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个字典,它提供了从实数元组到标识整数的映射。给定一个元组列表,其中包含的数字在字典中的公差范围内,但不完全等于字典中的值,我想生成相应整数的列表。在

示例:

tdict = {(0.334, 0.333, 0.333):1, (0.167, 0.666, 0.167):2, (0.5, 0.5, 0):3}
tlist = [(0.333, 0.333, 0.333), (0.16667, 0.6666667, 0.17), (0.34, 0.33, 0.33), (0.5001, 0.4999, 0.0)]
tol = 0.01

运行我想要的代码应该会产生结果

^{pr2}$

因为每个元组中的所有数字都在tdict中相应元组的给定公差范围内。我可以通过迭代tdict.keys()并分别比较每个方法来实现这一点,但我觉得应该有更好的方法。得到这些元组对应的整数的最有效的方法是什么?它不必涉及字典,这在我看来是最自然的。我用的是python3。在


Tags: 方法代码示例列表字典数字整数标识
3条回答

很明显,您希望将三维空间中的点投影到具有特定栅格间距(这与公差值直接相关)的三维栅格上,并创建某种直方图。为自己编写一个投影函数:它以任意的3元素列表/元组(描述空间中某个点的向量)为参数,并将其投影到某个网格点上。你这样做是为了充实你的字典,也是为了把它读出来。此外,关于字典中的键,我认为您应该使用整数元组而不是float,因为我不确定float是否可以完全相同。在

这是一个实现示例:

from collections import defaultdict
from random import random as rn

class Grid(object):
    def __init__(self, spacing):
        self.spacing = spacing
        self.griddict = defaultdict(int)

    def add_point(self, coords):
        """
        `vid`, a voxel id, is a tuple of indices, indicating one grid
        bin for each dimension, e.g. (1, 5, 2)
        rule: i_x = int(floor(x_coord / spacing))
        """
        vid = tuple([int(c//self.spacing) for c in coords])
        self.griddict[vid] += 1

    def get_point(self, coords):
        vid = tuple([int(c//self.spacing) for c in coords])
        return self.griddict[vid]

    def vid_centercoords(self, vid):
        """
        Return the real coordinates in space for a certain voxel,
        which is identified by its voxel id `vid` (a tuple of indices).
        """
        return tuple([(i-1)*self.spacing + self.spacing/2 for i in vid])



N = 20
fillpoints = [(rn(),rn(),rn()) for _ in xrange(N)]
testpoints = [(rn(),rn(),rn()) for _ in xrange(N)]

grid = Grid(spacing=0.3)

for p in fillpoints:
    grid.add_point(p)

print [grid.get_point(p) for p in testpoints]

作用:在三维空间中创建20个随机向量(所有坐标都在0和1之间)。它使用空间中的这些点填充三维栅格。网格在每个维度中的间距为0.3。空间中的这20个点中的每一个都被指定给网格中的某个体素(只是3D像素的一个单词)。每次指定都会将相应体素的计数器增加1(将网格渲染为直方图)。然后,用另一组随机的20个向量来读出体素。这些点再次投影到体素上,但这次计数器只是返回而不是增加。执行测试:

^{pr2}$

使用您的数据执行:

fillpoints = [(0.334, 0.333, 0.333), (0.167, 0.666, 0.167), (0.167, 0.666, 0.167), (0.5, 0.5, 0), (0.5, 0.5, 0), (0.5, 0.5, 0)]
testpoints = [(0.333, 0.333, 0.333), (0.16667, 0.6666667, 0.17), (0.34, 0.33, 0.33), (0.5001, 0.4999, 0.0)]

grid = Grid(spacing=0.03)
for p in fillpoints:
    grid.add_point(p)
print [grid.get_point(p) for p in testpoints]

{cd1>按要求打印。我没有深入思考过spacing=3*tolerance之间的关系。可能是错的。我只知道有一个确定的关系。证明/找到这个公式留给你作为练习:)

  1. 依次按到tlist的每个点的距离对tdict.keys()排序。在
  2. 挑选前几个并在tdict中查找它们。在

如果您有权访问numpy,则可以使用numpy.allclose检查匹配项:

>>> import numpy
>>> numpy.allclose((0.334, 0.333, 0.333), (0.333, 0.333, 0.333))
False
>>> numpy.allclose((0.334, 0.333, 0.333), (0.333, 0.333, 0.333), atol=0.1)
True

相关问题 更多 >

    热门问题