Ari*_*nda -5 python lambda defaultdict
我正在使用下面的python代码创建字典。但是我收到dct_structure变量的一个PEP 8警告。警告是:do not use a lambda expression use a def
from collections import defaultdict
dct_structure = lambda: defaultdict(dct_structure)
dct = dct_structure()
dct['protocol']['tcp'] = 'reliable'
dct['protocol']['udp'] = 'unreliable'
Run Code Online (Sandbox Code Playgroud)
我对python lambda表达式还不满意。因此,任何人都可以帮助我为以下两行python代码定义函数以避免PEP警告。
dct_structure = lambda: defaultdict(dct_structure)
dct = dct_structure()
Run Code Online (Sandbox Code Playgroud)
Python中的lambda本质上是具有笨拙的受限语法的匿名函数。警告只是说,假设您直接将其分配给变量-因此给lambda一个名称-您可以使用def,它具有更清晰的语法并将函数名称烘焙到函数对象中,从而提供更好的诊断。
您可以将代码段重写为
def dct_structure():
return defaultdict(dct_structure)
dct = dct_structure()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3349 次 |
| 最近记录: |