简体   繁体   English

如何在python中重复/扩展表达式

[英]how to repeat / expand expressions in python

What is the most pythonic way to repeat an expression in Python. 在Python中重复表达式的最pythonic方法是什么。

Context : A function is getting passed a dictionary (with possibly 20 elements) and I need to extract and use values from this dictionary if they exist . 上下文:一个函数正在传递一个字典(可能包含20个元素), 如果存在 ,我需要从该字典中提取和使用值。 Something like this : 像这样的东西:

x = dict_name['key1'] if dict_name['key1'] else ''

Now, instead of writing this logic 20 times for all 20 different keys, I would like to define this expression at one place and then use it repeatedly. 现在,我不想为所有20个不同的键编写此逻辑20次,而是想在一个地方定义此表达式,然后重复使用它。 It will be easier to maintain in future. 将来将更容易维护。 In "C/C++" programming languages, it makes a good case of #define or inline functions. 在“ C / C ++”编程语言中,它很好地体现了#defineinline函数。 What would be Pythonic way to do this in Python? 用Python做到这一点的Python方式是什么?

As you would have guessed, I am novice in Python. 如您所料,我是Python的新手。 So I appreciate your help on this or pointers to constructs for this in Python. 因此,感谢您在此方面的帮助或在Python中为此构造的指针。

Whether there is an "equivalent" to inline in Python depends on who you ask, and what you check. 在Python中是否有inline的“等价”项取决于您询问的人和检查的内容。

For no equivalent, eg: https://stackoverflow.com/a/6442497/2707864 对于无等效项,例如: https : //stackoverflow.com/a/6442497/2707864

For equivalent, eg: https://www.safaribooksonline.com/library/view/python-cookbook-3rd/9781449357337/ch07s06.html 对于等效项,例如: https : //www.safaribooksonline.com/library/view/python-cookbook-3rd/9781449357337/ch07s06.html

From a practical point of view, lambda would do the trick ( dict.get replaces your ternary conditional operator) 从实际的角度来看, lambda可以解决问题( dict.get替换您的三元条件运算符)

dict_get = lambda key : dict_name.get(key, '')

Or you can always define a one-line function. 或者,您始终可以定义单行函数。

def dict_get( key ) : dict_name.get( key, '' )

Pythonicity is quite often (always?) subjective. Pythonicity通常(总是?)是主观的。

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

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