简体   繁体   English

你如何找出一个值属于哪个对象?

[英]How can you find out which object a value belongs to?

Say I have a dictionary called dic:假设我有一本名为 dic 的字典:

dic = {"a":1, "b":2, "c":3}

And let's say I have some code, and later on, I provide the key dic["a"] to derive a value 1. How would I be able to inform the programme that the value 1 came from the key of "a" inside "dic", and not from say, a list, or another dic, and so on?假设我有一些代码,稍后,我提供了键 dic["a"] 来导出值 1。我如何才能通知程序值 1 来自内部的键“a” “dic”,而不是来自某个列表或另一个 dic 等等?

This is important because am writing a programme where there are many of the same values, but parts of the programme are going to run based upon where the value came from.这很重要,因为我正在编写一个程序,其中有许多相同的值,但程序的某些部分将根据值的来源运行。

Thanks.谢谢。

There is, as far as I know, no way to do what you're asking.据我所知,没有办法做你所要求的。 Data retrieved from dictionaries and other sources have no knowledge of the key that they were associated with originally.从字典和其他来源检索的数据不知道它们最初关联的键。

I think the cleanest method would be to have some kind of wrapper function that handles this for you and stores the data in an easy to use format:我认为最干净的方法是使用某种包装函数来为您处理此问题并以易于使用的格式存储数据:

from typing import Dict, NamedTuple

class Record(NamedTuple):
    amount: int
    source: str

def recording_get(dict: Dict[str, int], source: str) -> Record:
    return Record(dict[source], source)


dic = {"a":1, "b":2, "c":3}
rec = recording_get(dic, "a")
print(rec)  #  Prints Record(amount=1, source='a')

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM