前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python 小工具总结

python 小工具总结

作者头像
ke1th
发布2018-01-02 11:23:57
5210
发布2018-01-02 11:23:57
举报

总结一些python编程中可能会用到的一些小工具

namedtuple

给tuple 起个名字

代码语言:javascript
复制
def namedtuple(typename, field_names, verbose=False, rename=False):
  """Returns a new subclass of tuple with named fields.

    >>> Point = namedtuple('Point', ['x', 'y'])
    >>> Point.__doc__                   # docstring for the new class
    'Point(x, y)'
    >>> p = Point(11, y=22)             # instantiate with positional args or keywords
    >>> p[0] + p[1]                     # indexable like a plain tuple
    33
    >>> x, y = p                        # unpack like a regular tuple
    >>> x, y
    (11, 22)
    >>> p.x + p.y                       # fields also accessible by name
    33
    >>> d = p._asdict()                 # convert to a dictionary
    >>> d['x']
    11
    >>> Point(**d)                      # convert from a dictionary
    Point(x=11, y=22)
    >>> p._replace(x=100)               # _replace() is like str.replace() but targets named fields
    Point(x=100, y=22)

    """

from collections import namedtuple
NamedTuple = namedtuple("NamedTuple", ['output', 'stride']) # 返回一个类

tup1 = NamedTuple(output=54, stride=2) 
print(tup1[1], tup1)

OrderedDict

代码语言:javascript
复制
# 记录了插入元素顺序的 dict
from collections import OrderedDict

ordered_dict = OrderedDict()

ordered_dict['he'] = 'hello'
ordered_dict['be'] = 'bello'
print(ordered_dict)
# OrderedDict([('he', 'hello'), ('be', 'bello')])
# 遍历方法与 dict 一致
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • namedtuple
  • OrderedDict
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档