简体   繁体   English

使用同一词典中的另一个值声明词典?

[英]Declaring a dictionary using another value within the same dictionary?

I'm using python trying to basically do this: 我正在使用python尝试基本上做到这一点:

myDict = {"key1" : 1, "key2" : myDict["key1"]+1}

...if you catch my drift. ...如果你赶上我的漂流。 Possible without using multiple statements? 不使用多个语句可能吗?

EDIT: Also, if anyone could tell me a better way to state this question more clearly that would be cool. 编辑:另外,如果有人可以告诉我一种更好的方法来更清楚地陈述这个问题,那将很酷。 I don't really know how to word what I'm asking. 我真的不知道该怎么说。

EDIT2: Seems to be some confusion - yes, it's more complex than just "key2":1+1, and what I'm doing is mostly for code readability as it will get messy if I have to 2-line it. EDIT2:似乎有些混乱-是的,它比“ key2”:1 + 1更复杂,我正在做的主要是为了代码可读性,因为如果必须两行代码,它将变得混乱。

Here's a bit more accurate code sample of what I'm trying to do...though it's still not nearly as complex as it gets :P 这是我要执行的操作的更准确的代码示例...尽管它仍不像它变得复杂:P

lvls={easy:  {mapsize:(10,10), winPos:(mapsize[0]-1,mapsize[1]-1)},
      medium:{mapsize:(15,15), winPos:(mapsize[0]-RANDOMINT,mapsize[1]-1)},
      hard:  {mapsize:(20,20), winPos:(mapsize[0]-RANDOMINT,mapsize[1]-RANDOMINT)}
     }

No, this isn't possible in general without using multiple statements. 不,通常不使用多条语句就不可能。

In this particular case, you could get around it in a hacky way. 在这种情况下,您可能会以骇人的方式解决它。 For example: 例如:

myDict = dict(zip(("key1", "key2"), itertools.count(1))

However, that will only work when you want to specify a single start value and everything else will be sequential, and presumably that's not general enough for what you want. 但是,这仅在您要指定单个起始值并且其他所有内容都将是顺序的时才起作用,并且可能这对于您想要的内容来说不够通用。

If you're doing this kind of thing a lot, you could wrap those multiple statements up in some suitably-general function, so that each particular instance is just a single expression. 如果您经常做这种事情,则可以将这些多个语句包装在适当的通用函数中,以便每个特定实例只是一个表达式。 For example: 例如:

def make_funky_dict(*args):
    myDict = {}
    for key, value in zip(*[iter(a)]*2):
        if value in myDict:
            value = myDict[value] + 1
        myDict[key] = value
    return myDict

myDict = make_funky_dict("key1", 1, "key2", "key1")

But really, there's no good reason not to use multiple statements here, and it will probably be a lot clearer, so… I'd just do it that way. 但是,实际上,没有充分的理由不在此处使用多个语句,它可能会更加清晰,所以……我就是这样做的。

It's not possible without using multiple statements, at least not using some of the methods from your problem statement. 不使用多个语句,至少不使用问题语句中的某些方法是不可能的。 But here's something, using dict comprehension: 但是这里有一些使用dict理解的东西:

>>> myDict = {"key" + str(key): value for (key, value) in enumerate(range(7))}
>>> myDict
{'key0': 0,
 'key1': 1,
 'key2': 2,
 'key3': 3,
 'key4': 4,
 'key5': 5,
 'key6': 6}

Of course those aren't in order, but they're all there. 当然,这些不是按顺序排列的,但是它们都在那里。

The only variable you are trying to use is an integer. 您尝试使用的唯一变量是整数。 How about a nice function: 一个好的函数怎么样:

def makelevel(size,jitterfunc=lambda:0):
    return {'mapsize':(size,size), 'winPos':(size-1+jitterfunc(),size-1+jitterfunc())}

lvls = {hardness,makelevel(size) for hardness, size in [('easy',10),('medium',15), ('hard',20)]}

Of course, this function looks a bit like a constructor. 当然,此函数看起来有点像构造函数。 Maybe you should be using objects? 也许您应该使用对象?

If you want a dict that will allow you to to have values that are evaluated on demand you can do something like this: 如果您想要一个可以让您拥有按需评估的值的字典,则可以执行以下操作:

class myDictType(dict):                                                                
  def __getitem__(self, key):                                                      
    retval = dict.__getitem__(self,key)                                            
    if type(retval) == type(lambda: 1):                                            
      return retval()                                                              
    return retval                                                                  

myDict = myDictType()                                                                     

myDict['bar'] = lambda: foo['foo'] + 1                                                

myDict['foo'] = 1                                                                     
print myDict['bar']   #This'll print a 2                                                       
myDict['foo'] = 2                                                                   
print myDict['bar']   #This'll print a 3                                                     

This overrides __getitem__ in the dictionary to return whatever is stored in it (like a normal dictionary,) unless what is stored there is a lambda. 这将覆盖字典中的__getitem__,以返回存储在其中的任何内容(就像普通字典一样),除非存储的内容是lambda。 If the value is a lambda, it instead evaluates it and returns the result. 如果该值为lambda,则将其求值并返回结果。

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

相关问题 如何过滤字典值(在另一个字典中) - How to filter a dictionary value (within another dictionary) 将一个字典作为值添加到另一个具有相同键的字典中 - Add a dictionary as a value to another dictionary with the same key 在另一本词典中对词典进行排序 - sort a dictionary within another dictionary 将字典值映射到同一数据文件中另一个字典中的值 - map dictionary value to the value in another dictionary in the same data file 如果嵌套字典中存在最大值,则在同一字典中打印另一个值 - If max value exists in nested dictionary, print another value in same dictionary 根据同一个字典中的另一个,提取熊猫中一个字典键的值 - Extracting value for one dictionary key in Pandas based on another in the same dictionary python字典键,指向同一字典中另一个键的值 - python dictionary key pointing to value of another key in the same dictionary 如果字典在另一个字典中,则更改字典的值 - Change value of dictionary if it is in another dictionary 在一行中将字典声明并附加到一行中 - Declaring and appending a list within a dictionary in one line 对于另一个词典中的一个词典,如何按值对其进行排序并比较该词典中的不同项目 - For a dictionary inside another dictionary how do you sort it by the value and compare different items within the dictionary
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM