Python 3更改for循环中字典键的值不起作用 [英] Python 3 changing value of dictionary key in for loop not working

查看:664
本文介绍了Python 3更改for循环中字典键的值不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有无法正常工作的python 3代码:

I have python 3 code that is not working as expected:

def addFunc(x,y):
    print (x+y)

def subABC(x,y,z):
    print (x-y-z)

def doublePower(base,exp):
    print(2*base**exp)

def  RootFunc(inputDict):
    for k,v in inputDict.items():
        if v[0]==1:
            d[k] = addFunc(*v[1:])
        elif v[0] ==2:
            d[k] = subABC(*v[1:])
        elif  v[0]==3:
            d[k] = doublePower(*v[1:])


d={"s1_7":[1,5,2],"d1_6":[2,12,3,3],"e1_3200":[3,40,2],"s2_13":[1,6,7],"d2_30":[2,42,2,10]}
RootFunc(d)

#test to make sure key var assignment works
print(d)

我得到:

{'d2_30': None, 's2_13': None, 's1_7': None, 'e1_3200': None, 'd1_6': None}

我期望:

{'d2_30': 30, 's2_13': 13, 's1_7': 7, 'e1_3200': 3200, 'd1_6': 6}

怎么了?

半相关:我知道字典是无序的,但是python为什么选择了这个顺序呢?它会通过随机化器来运行密钥吗?

Semi related: I know dictionaries are unordered but is there any reason why python picked this order? Does it run the keys through a randomizer?

推荐答案

print不返回值.它返回None,因此每次调用函数时,它们都会打印到标准输出并返回None.尝试像这样将所有print语句更改为return:

print does not return a value. It returns None, so every time you call your functions, they're printing to standard output and returning None. Try changing all print statements to return like so:

 def addFunc(x,y):
     return x+y

这会将值x+y返回给所谓的函数.

This will give the value x+y back to whatever called the function.

您的代码的另一个问题(除非您打算这样做)是,您定义一个字典d,然后在定义函数时,您正在使用此字典d,而不是使用'input字典':

Another problem with your code (unless you meant to do this) is that you define a dictionary d and then when you define your function, you are working on this dictionary d and not the dictionary that is 'input':

def  RootFunc(inputDict):
    for k,v in inputDict.items():
        if v[0]==1:
            d[k] = addFunc(*v[1:])

您是否打算始终更改d不是您要迭代的字典,inputDict?

Are you planning to always change d and not the dictionary that you are iterating over, inputDict?

可能还有其他问题(例如,函数中接受可变数量的参数),但是一次解决一个问题是很好的.

There may be other issues as well (accepting a variable number of arguments within your functions, for instance), but it's good to address one problem at a time.

有关功能的其他说明:

下面是一些伪代码,试图传达函数的使用方式:

Here's some sort-of pseudocode that attempts to convey how functions are often used:

def sample_function(some_data):
     modified_data = []
     for element in some_data:
          do some processing
          add processed crap to modified_data
     return modified_data

功能被认为是黑匣子",这意味着您可以对它们进行结构化,以便可以将一些数据转储到它们中,并且它们始终执行相同的操作,并且可以一遍又一遍地调用它们.它们将使用return值或yield值,或更新某些值或属性或某些内容(后者称为副作用").目前,只需注意return语句.

Functions are considered 'black box', which means you structure them so that you can dump some data into them and they always do the same stuff and you can call them over and over again. They will either return values or yield values or update some value or attribute or something (the latter are called 'side effects'). For the moment, just pay attention to the return statement.

另一个有趣的事情是,函数具有作用域",这意味着当我使用参数的伪名称定义它时,实际上我不必具有一个名为"some_data"的变量.我可以将所需的任何内容传递给函数,但是在函数内部,我可以引用假名称并创建其他仅在函数上下文内才有意义的变量.

Another interesting thing is that functions have 'scope' which means that when I just defined it with a fake-name for the argument, I don't actually have to have a variable called "some_data". I can pass whatever I want to the function, but inside the function I can refer to the fake name and create other variables that really only matter within the context of the function.

现在,如果我们在上面运行我的函数,它将继续处理数据:

Now, if we run my function above, it will go ahead and process the data:

 sample_function(my_data_set)

但这通常是没有意义的,因为该函数应该返回某些内容,而我对返回的内容不做任何操作.我应该做的是将函数的值及其参数分配给某个容器,以便保留已处理的信息.

But this is often kind of pointless because the function is supposed to return something and I didn't do anything with what it returned. What I should do is assign the value of the function and its arguments to some container so I can keep the processed information.

my_modified_data = sample_function(my_data_set)

这是使用函数的一种非常常见的方式,您可能会再次看到它.

This is a really common way to use functions and you'll probably see it again.

一种解决问题的简单方法:

考虑到所有这些,这是一种解决您的问题的方法,该方法来自一个非常常见的编程范例:

Taking all this into consideration, here is one way to solve your problem that comes from a really common programming paradigm:

def  RootFunc(inputDict):
    temp_dict = {}
    for k,v in inputDict.items():
        if v[0]==1:
            temp_dict[k] = addFunc(*v[1:])
        elif v[0] ==2:
            temp_dict[k] = subABC(*v[1:])
        elif  v[0]==3:
            temp_dict[k] = doublePower(*v[1:])
    return temp_dict


  inputDict={"s1_7":[1,5,2],"d1_6":[2,12,3,3],"e1_3200":[3,40,2],"s2_13":[1,6,7],"d2_30"[2,42,2,10]}
  final_dict = RootFunc(inputDict)

这篇关于Python 3更改for循环中字典键的值不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆