简体   繁体   English

python,字典值是对象,该对象可以从自身内部的函数访问其自己的键值吗?

[英]python, dictionary value is object, can that object access its own key value from a function within itself?

I'm using a dictionary in python to make what is basically an infinite 2d array by using a tuple as the key 我正在使用python中的字典,通过使用元组作为键来制作基本上是无限的2d数组

grid = {}
grid[(0,0)] = cell()

the value 'cell' is a new object. 值“ cell”是一个新对象。 Can I have, say, a function within that object that is able to get its key value? 我可以说该对象中有一个能够获取其键值的函数吗? ie. 即。 (0,0) (0,0)

I could just put that data in the object itself but then I'd have it existing twice which seems like bad programming. 我可以将这些数据放在对象本身中,但是然后我将它存在两次,这似乎是不好的编程。 Thanks! 谢谢!

class cell(object):
     def my_idx(self,grid):
         return grid.keys()[grid.values().index(self)]

then call it 然后叫它

some_cell.my_idx(grid)

This should work: 这应该工作:

class Cell(object):

    def get_idx(self, grid):
        """
        >>> cell = Cell()
        >>> cell.get_idx({(0, 0): cell})
        (0, 0)

        >>> cell = Cell()
        >>> cell.get_idx({(0, 0): Cell(), (1, 1): cell, (2, 2): Cell()})
        (1, 1)
        """
        return [x[0] for x in grid.items() if x[1] == self][0]

Just notice that it won't give you realiable results if the object is more than once in the dict and it would raise an exception if the object isn't in the dict. 请注意,如果对象在字典中不止一次,它将不会给您带来可实现的结果;如果对象不在字典中,它将引发异常。

Also it could be slow on very large grids. 同样,在非常大的网格上它可能会变慢。

Your questions implies that there's a 1:1 mapping between dict keys and their values, which is not true. 您的问题意味着字典键和它们的值之间存在1:1的映射,这是不正确的。 Take this code: 采取以下代码:

grid = {}
c = cell()
grid[(0,0)] = c
grid[(0,1)] = c

That's perfectly valid in python, even if your use case does not allow it. 即使在用例不允许的情况下,这在python中也是完全有效的。 What index should the function you are looking for return for c ? 您要寻找的函数应该为c返回什么索引?

Storing the data twice does not have to be bad programming style, but your memory might be limited. 两次存储数据不一定是不好的编程风格,但是您的内存可能有限。 If your cell needs to know it's index, it must have that data. 如果您的cell需要知道它的索引,则必须具有该数据。 If you see your cells as a list of items, the dict becomes just a index for faster access. 如果您将单元格视为项目列表,则dict只是索引,可加快访问速度。 And having indexes for faster access is of course no bad programming style. 并且拥有索引以实现更快的访问当然不是不好的编程风格。 ;-) ;-)

There are two separate issues here... first, to access the grid from within cell, I would have cell 's constructor take a reference to grid as a mandatory argument. 这里有两个独立的问题...首先,要从单元内部访问网格,我将让cell的构造函数将对网格的引用作为强制参数。

grid = {}
grid[(0,0)] = cell(grid)

and

class cell:
  def __init__(self, gridRef):
    self.grid = gridRef

But, accessing the key is more challenging. 但是,访问密钥更具挑战性。 One reason is that a dictionary is not a one-to-one mapping, so the same cell object may have multiple keys in your dictionary. 原因之一是词典不是一对一的映射,因此同一个单元格对象在词典中可能有多个键。 You'd need to iterate over your keys and look for it, either manually or through flipping the dictionary. 您需要手动或通过翻转字典来遍历键并寻找它。 How about making your cell constructor take the key as well? 如何使您的cell构造函数也采用密钥?

grid = {}
grid[(0,0)] = cell(grid, (0,0))

If that's too redundant, then maybe something like this? 如果那太多余了,那么也许是这样吗?

def addToGrid(myDict, myCell):
  myDict[myCell.key()] = myCell

and then... 接着...

grid = {}
addToGrid(grid, cell(grid, (0, 0)))

where your cell class takes the dictionary key as the second argument and returns it via the key() method. 您的cell类将字典键作为第二个参数,并通过key()方法返回它。

Give your cell class an address attribute, which is a two-tuple, eg (0,0) . 给您的cell类一个address属性,该属性是一个二元组,例如(0,0) Give the cell class a __hash__ method, which returns hash(self.address) . cell类一个__hash__方法,该方法返回hash(self.address)

class cell:
    def __init__(self,address):
        self.address = address

    def __hash__(self):
        return hash(self.address)

    def __eq__(self):
        return hash(self) == hash(other)

You can still access cells by their address, but the cells know where they belong. 您仍然可以通过其地址访问单元格,但是单元格知道它们的位置。

>>> c = cell((0,0))
>>> c
<so.cell instance at 0xb74c6a2c>
>>> grid = dict()
>>> grid[c] = c
>>> grid[c]
<so.cell instance at 0xb74c6a2c>
>>> grid[(0,0)]
<so.cell instance at 0xb74c6a2c>

I'm not sure what else your cell s need to know and/or do, but if you're just doing numerical stuff here, I'd highly recommend the scipy.sparse module. 我不确定您的cell需要知道和/或做什么,但是如果您只是在这里做数字工作,我强烈建议使用scipy.sparse模块。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在字典/ hashmap(在python中)中使用对象作为自己的键是否正常? - Is it normal to use an object as its own key in a dictionary/hashmap (in python)? 您可以从该字典中的 function 访问 python 字典键的值吗? - Can you access a python dictionary key's value from a function in that dictionary? 在python中的函数内将键和值添加到字典中 - Adding key and value to a dictionary within a function in python Python request.json()对象作为字典无法使用hasattr()或object.keys()调用中的值识别其自身的键 - Python requests.json() object as dictionary does not recognize its own keys with hasattr() or value in object.keys() call 如何从 Python 中的 object 返回的字典中访问特定值 - How can I access a specific value from the dictionary returned by this object in Python python类可以访问其自己的对象的属性吗? - can a python class access attribute of its own object? Python-对象的参数及其值作为函数的参数 - Python - parameter of an object and its value as argument of a function Python:获取字典值内的键值 - python: getting the key value within the value of dictionary 使用文本文件创建字典时出现问题,该字典以字长为键,实际字本身为 Python 中的值 - Problem with using a text file to create a dictionary that has word length as its key and the actual word itself as the value in Python 如何从 python 中的 object 列中的多个字典键和值中提取最大值和相应键 dataframe - How to extract max value and respective key from multiple dictionary key & values inside an object column in python dataframe
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM