热卖商品
新闻详情
对namedtuples使用下划线 - 问答 - Python中文网
来自 : www.cnpython.com/qa/431...
发布时间:2021-03-25
it_consumes = (lambda it, n=None: deque(it, maxlen=0) or None if n is None else next(islice(it, n, n), None)) def update_d(d, **kwargs): d.update(kwargs) return d
网友2楼 ·
网友3楼 ·
3天前<p>我正在用Python构建一个SQL仿真器,为了存储行,我想使用namedtuples,因为我可以轻松地处理带有select、orderby和where的复杂查询。我从普通元组开始...<p>我正在用Python构建一个SQL仿真器,为了存储行,我想使用namedtuples,因为我可以轻松地处理带有select、orderby和where的复杂查询。我从普通元组开始,但我经常发现自己在寻找行的属性,并且需要维护列的顺序,所以我得到了namedtuples。在</p> <p>问题是对namedtuples使用下划线
好的,现在让我们取一个tuple的t = \'a\', \'b\', \'c\', \'_can\'并执行以下操作:
MyClass = type(\'MyClass\', tuple(), update_d({k : None for k in t}, __init__=lambda self, **kwargs: it_consumes( setattr(self, k, v) for k,v in kwargs.items())))
然后可以这样使用:
obj = MyClass(a=5, b=6, _can=\'haz\')print(\'obj._can:\', obj._can)

可以使用rename=True参数避免ValueError
from collections import namedtuplea = namedtuple(\"Table\", \"_col1 _col2 _col3 col4\", rename=True)print(a._fields)
(\'_0\', \'_1\', \'_2\', \'col4\')
@Edit1您可能需要跟踪哪些字段已更改
^{pr2}${\'_col3\': \'_2\', \'_col1\': \'_0\', \'col4\': \'col4\', \'_col2\': \'_1\'}

考虑使用OrderedDict类型。您可以通过括号语法访问任何字符串名称的字段,并最终使用“.items”将其转换为元组。在
from collections import OrderedDictordered_form = OrderedDict([(\"col1\", \'Apple\'), (\"col2\", \'Orange\'), (\"_col3\", \'Banana\')])ordered_form[\"_col3\"] = \'Grapefruit\'tuple_form = tuple([i[1] for i in list(ordered_form.items())])print(tuple_form)相关问题
3天前<p>我正在用Python构建一个SQL仿真器,为了存储行,我想使用namedtuples,因为我可以轻松地处理带有select、orderby和where的复杂查询。我从普通元组开始...<p>我正在用Python构建一个SQL仿真器,为了存储行,我想使用namedtuples,因为我可以轻松地处理带有select、orderby和where的复杂查询。我从普通元组开始,但我经常发现自己在寻找行的属性,并且需要维护列的顺序,所以我得到了namedtuples。在</p> <p>问题是对namedtuples使用下划线
本文链接: http://cannameds.immuno-online.com/view-724762.html
发布于 : 2021-03-25
阅读(0)
最新动态
2021-03-25
2021-03-25
2021-03-25
2021-03-25
2021-03-25
2021-03-25
2021-03-25
2021-03-25
2021-03-25
2021-03-25
2021-03-25
2021-03-25