2024-05-23 17:29:02 发布
网友
我想这样做:
parsetable = { # ... declarations: { token: 3 for token in [_id, _if, _while, _lbrace, _println] }.update({_variable: 2}), #... }
但是这不起作用,因为update不返回任何内容。除了显式地写下整个dict之外,还有什么简单的方法可以做到这一点?在
使用dict()和元组的列表理解+额外的部分应该是可能的,但这很尴尬。在
我认为您提到的使用dict()和元组列表的方法就是这样做的:
dict([(x, 3) for x in [_id, _if, _while, _lbrace, _println]] + [(_variable, 2)])
如果你真的想用听写来理解,你可以这样做:
但是,为了让您知道,如果您想要update return something,可以编写一个func,如下所示:
import copy def updated_dict(first_dict, second_dict): f = copy.deepcopy(first_dict) f.update(second_dict) return f
为了清晰起见,我把它分开,然后应用@Mark Byers的第二个建议来理解听写:
type2 = [_variable] type3 = [_id, _if, _while, _lbrace, _println] parsetable = { declarations: { token : 2 if token in type2 else 3 for token in type2+type3 } }
这使事情变得非常清楚,并且是可扩展的,同时将相关项放在一起以便于查找和/或修改。在
我认为您提到的使用dict()和元组列表的方法就是这样做的:
如果你真的想用听写来理解,你可以这样做:
^{pr2}$但是,为了让您知道,如果您想要update return something,可以编写一个func,如下所示:
为了清晰起见,我把它分开,然后应用@Mark Byers的第二个建议来理解听写:
这使事情变得非常清楚,并且是可扩展的,同时将相关项放在一起以便于查找和/或修改。在
相关问题 更多 >
编程相关推荐