简体   繁体   English

Python在使用值两次时避免使用变量?

[英]Python avoiding using a variable when using a value twice?

I currently have: 我目前有:

tmp = myfunc()
mydict[mykey] = tmp
return tmp

..which seems a little too long. ..这似乎有点太长了。 In javascript, I could just do: 在javascript中,我可以这样做:

return (mydict[mykey] = myfunc()) 

Is the above Python code the accepted way to do it, or is there something else? 上面的Python代码是可以接受的方式,还是还有别的东西?

edit: I'm aware of the possibility of doing: 编辑:我知道做的可能性:

mydict[mykey] = myfunc()
return mydict[mykey]

..but I wouldn't want to do a key lookup twice. ..但我不想做两次密钥查找。 Unless 除非

tmp = mydict[mykey] = myfunc()
return tmp

You can do this if you want less lines of code: 如果你想要更少的代码行,你可以这样做:

mydict[mykey] = myfunc()
return mydict[mykey]

Assignment isn't an expression in Python, though, so you can't do the javascript version. 但是,赋值不是Python中的表达式,因此您无法执行javascript版本。


EDIT: If you know the key is not in the dictionary, you can do this: 编辑:如果你知道密钥不在字典中,你可以这样做:

return mydict.setdefault(mykey, myfunc())

setdefault is a lookup function that sets the key to the 2nd value if the key is not in the dictionary. setdefault是一个查找函数,如果键不在字典中,则将键设置为第二个值。


You could also write a helper function: 你也可以写一个辅助函数:

def set_and_return(d, k, v):
    d[k] = v 
    return v

Then, everywhere else, you can do: 然后,在其他地方,你可以这样做:

return set_and_return(mydict, mykey, myfunc())

Opinions vary but here is my $.02. 意见各不相同,但这是我的$ .02。

  1. Please do not use default dict. 请不要使用默认字典。 If I'm reading your code, I might not know what you know, that there is no key in the dict. 如果我正在读你的代码,我可能不知道你知道什么,这个词没有关键词。 Someone could later update the code and violate that silent assumption and the code will break. 有人可能会在以后更新代码并违反该默认假设,代码将中断。
  2. Please do not use the "set_and_return" function. 请不要使用“set_and_return”功能。 Your code might be clever but it's less readable. 您的代码可能很聪明,但可读性较差。 More lines, harder to follow and the function lookup costs the same as the dict lookup. 更多行,更难以遵循,函数查找与dict查找相同。
  3. @gnibbler has a nice "fewer lines of code" solution but I wouldn't suggest it and reading a lot of python source I rarely see that syntax (more at the start of a function than anywhere else) @gnibbler有一个很好的“更少的代码行”解决方案,但我不建议它和阅读很多python源我很少看到语法(更多在函数的开头比其他任何地方)

I appreciate how it happens in javascript but for the accepted way to do it: I vote for your original format, easiest to read and understand and no slower or less efficient than any other solution. 我很欣赏它是如何在javascript中发生的,但是对于可接受的方式:我投票支持您的原始格式,最容易阅读和理解,并且没有比任何其他解决方案更慢或更低效。

tmp = myfunc()
mydict[mykey] = tmp
return tmp

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

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