最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

python中namedtuple函數(shù)的用法解析

 更新時間:2022年08月31日 11:51:59   作者:IT之一小佬  
這篇文章主要介紹了python中namedtuple函數(shù)的用法解析,文章圍繞主題展開詳細的內(nèi)容介紹,具有一定的參考價值,感興趣的小伙伴可以參考一下

源碼解釋:

def namedtuple(typename, field_names, *, rename=False, defaults=None, module=None):
    """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)
    """

語法結(jié)構(gòu):

namedtuple(typename, field_names, *, rename=False, defaults=None, module=None)
  • typename: 代表新建的一個元組的名字。
  • field_names: 是元組的內(nèi)容,是一個類似list的[‘x’,‘y’]

命名元組,使得元組可像列表一樣使用key訪問(同時可以使用索引訪問)。

collections.namedtuple 是一個工廠函數(shù),它可以用來構(gòu)建一個帶字段名的元組和一個有名字的類.

創(chuàng)建一個具名元組需要兩個參數(shù),一個是類名,另一個是類的各個字段的名字。

存放在對應字段里的數(shù)據(jù)要以一串參數(shù)的形式傳入到構(gòu)造函數(shù)中(注意,元組的構(gòu)造函數(shù)卻只接受單一的可迭代對象)。

命名元組還有一些自己專有的屬性。最有用的:類屬性_fields、類方法 _make(iterable)和實例方法_asdict()。

示例代碼1:

from collections import namedtuple
 
# 定義一個命名元祖city,City類,有name/country/population/coordinates四個字段
city = namedtuple('City', 'name country population coordinates')
tokyo = city('Tokyo', 'JP', 36.933, (35.689, 139.69))
print(tokyo)
 
# _fields 類屬性,返回一個包含這個類所有字段名稱的元組
print(city._fields)
 
# 定義一個命名元祖latLong,LatLong類,有l(wèi)at/long兩個字段
latLong = namedtuple('LatLong', 'lat long')
delhi_data = ('Delhi NCR', 'IN', 21.935, latLong(28.618, 77.208))
 
# 用 _make() 通過接受一個可迭代對象來生成這個類的一個實例,作用跟City(*delhi_data)相同
delhi = city._make(delhi_data)
 
# _asdict() 把具名元組以 collections.OrderedDict 的形式返回,可以利用它來把元組里的信息友好地呈現(xiàn)出來。
print(delhi._asdict())

運行結(jié)果:

示例代碼2:

from collections import namedtuple
 
Person = namedtuple('Person', ['age', 'height', 'name'])
data2 = [Person(10, 1.4, 'xiaoming'), Person(12, 1.5, 'xiaohong')]
print(data2)
 
res = data2[0].age
print(res)
 
res2 = data2[1].name
print(res2)

運行結(jié)果:

示例代碼3:

from collections import namedtuple
card = namedtuple('Card', ['rank', 'suit'])  # 定義一個命名元祖card,Card類,有rank和suit兩個字段
class FrenchDeck(object):
    ranks = [str(n) for n in range(2, 5)] + list('XYZ')
    suits = 'AA BB CC DD'.split()  # 生成一個列表,用空格將字符串分隔成列表
 
    def __init__(self):
        # 生成一個命名元組組成的列表,將suits、ranks兩個列表的元素分別作為命名元組rank、suit的值。
        self._cards = [card(rank, suit) for suit in self.suits for rank in self.ranks]
        print(self._cards)
 
    # 獲取列表的長度
    def __len__(self):
        return len(self._cards)
    # 根據(jù)索引取值
    def __getitem__(self, item):
        return self._cards[item]
f = FrenchDeck()
print(f.__len__())
print(f.__getitem__(3))

運行結(jié)果:

示例代碼4:

from collections import namedtuple
 
person = namedtuple('Person', ['first_name', 'last_name'])
 
p1 = person('san', 'zhang')
print(p1)
print('first item is:', (p1.first_name, p1[0]))
print('second item is', (p1.last_name, p1[1]))

運行結(jié)果:

示例代碼5:   【_make 從存在的序列或迭代創(chuàng)建實例】

from collections import namedtuple
course = namedtuple('Course', ['course_name', 'classroom', 'teacher', 'course_data'])
math = course('math', 'ERB001', 'Xiaoming', '09-Feb')
print(math)
print(math.course_name, math.course_data)
course_list = [
    ('computer_science', 'CS001', 'Jack_ma', 'Monday'),
    ('EE', 'EE001', 'Dr.han', 'Friday'),
    ('Pyhsics', 'EE001', 'Prof.Chen', 'None')
]
for k in course_list:
    course_i = course._make(k)
    print(course_i)

運行結(jié)果:

示例代碼6:    【_asdict 返回一個新的ordereddict,將字段名稱映射到對應的值】

from collections import namedtuple
person = namedtuple('Person', ['first_name', 'last_name'])
zhang_san = ('Zhang', 'San')
p = person._make(zhang_san)
print(p)
# 返回的類型不是dict,而是orderedDict
print(p._asdict())

運行結(jié)果:

示例代碼7:   【_replace 返回一個新的實例,并將指定域替換為新的值】

from collections import namedtuple
person = namedtuple('Person', ['first_name', 'last_name'])
zhang_san = ('Zhang', 'San')
p = person._make(zhang_san)
print(p)
p_replace = p._replace(first_name='Wang')
print(p_replace)
print(p)
p_replace2 = p_replace._replace(first_name='Dong')
print(p_replace2)

運行結(jié)果:

示例代碼8:   【_fields 返回字段名】

from collections import namedtuple
person = namedtuple('Person', ['first_name', 'last_name'])
zhang_san = ('Zhang', 'San')
p = person._make(zhang_san)
print(p)
print(p._fields)

運行結(jié)果:

示例代碼9:   【利用fields可以將兩個namedtuple組合在一起】

from collections import namedtuple
person = namedtuple('Person', ['first_name', 'last_name'])
print(person._fields)
degree = namedtuple('Degree', 'major degree_class')
print(degree._fields)
person_with_degree = namedtuple('person_with_degree', person._fields + degree._fields)
print(person_with_degree._fields)
zhang_san = person_with_degree('san', 'zhang', 'cs', 'master')
print(zhang_san)

運行結(jié)果:

示例代碼10:   【field_defaults】

from collections import namedtuple
person = namedtuple('Person', ['first_name', 'last_name'], defaults=['san'])
print(person._fields)
print(person._field_defaults)
print(person('zhang'))
print(person('Li', 'si'))

運行結(jié)果:

示例代碼11:   【namedtuple是一個類,所以可以通過子類更改功能】

from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(4, 5)
print(p)
class Point(namedtuple('Point', ['x', 'y'])):
    __slots__ = ()
 
    @property
    def hypot(self):
        return self.x + self.y
    def hypot2(self):
        return self.x + self.y
    def __str__(self):
        return 'result is %.3f' % (self.x + self.y)
aa = Point(4, 5)
print(aa)
print(aa.hypot)
print(aa.hypot2)

運行結(jié)果:

示例代碼12:   【注意觀察兩種寫法的不同】

from collections import namedtuple
 
Point = namedtuple("Point", ["x", "y"])
p = Point(11, 22)
print(p)
print(p.x, p.y)
 
# namedtuple本質(zhì)上等于下面寫法
class Point2(object):
    def __init__(self, x, y):
        self.x = x
        self.y = y
o = Point2(33, 44)
print(o)
print(o.x, o.y)

運行結(jié)果:

到此這篇關(guān)于python中namedtuple函數(shù)的用法解析的文章就介紹到這了,更多相關(guān)python namedtuple內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Python二次規(guī)劃和線性規(guī)劃使用實例

    Python二次規(guī)劃和線性規(guī)劃使用實例

    這篇文章主要介紹了Python二次規(guī)劃和線性規(guī)劃使用實例,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2019-12-12
  • pytorch中的 .view()函數(shù)的用法介紹

    pytorch中的 .view()函數(shù)的用法介紹

    這篇文章主要介紹了pytorch中的 .view()函數(shù)的用法,主要介紹兩種方法手動調(diào)整size和自動調(diào)整size,下面具體方法分析需要的小伙伴可以參考一下
    2022-03-03
  • python 查找文件名包含指定字符串的方法

    python 查找文件名包含指定字符串的方法

    今天小編就為大家分享一篇python 查找文件名包含指定字符串的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-06-06
  • Python中__init__和__new__的區(qū)別詳解

    Python中__init__和__new__的區(qū)別詳解

    這篇文章主要介紹了Python中__init__和__new__的區(qū)別詳解,并著重說明了__new__的作用及什么情況下使用__new__,需要的朋友可以參考下
    2014-07-07
  • Python字符串類型及格式化問題

    Python字符串類型及格式化問題

    這篇文章主要介紹了Python字符串類型及格式化問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2023-02-02
  • Python利用Telegram機器人搭建消息提醒

    Python利用Telegram機器人搭建消息提醒

    對開發(fā)者來說,Telgram最吸引人的地方估計是 Telgram bot,你可以在建個機器人來做些事情。本文就將利用Telegram機器人搭建消息提醒,感興趣的可以參考一下
    2022-06-06
  • python中celery的基本使用詳情

    python中celery的基本使用詳情

    這篇文章主要介紹了python中celery的基本使用詳情,Celery 是由Python 編寫的簡單,靈活,可靠的用來處理大量信息的分布式系統(tǒng),它同時提供操作和維護分布式系統(tǒng)所需的工具。Celery 專注于實時任務處理,支持任務調(diào)度
    2022-09-09
  • TensorFlow中關(guān)于tf.app.flags命令行參數(shù)解析模塊

    TensorFlow中關(guān)于tf.app.flags命令行參數(shù)解析模塊

    這篇文章主要介紹了TensorFlow中關(guān)于tf.app.flags命令行參數(shù)解析模塊,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-11-11
  • python用plt畫圖時,cmp設(shè)置方法

    python用plt畫圖時,cmp設(shè)置方法

    今天小編就為大家分享一篇python用plt畫圖時,cmp設(shè)置方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-12-12
  • django rest framework 過濾時間操作

    django rest framework 過濾時間操作

    這篇文章主要介紹了django rest framework 過濾時間操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-07-07

最新評論

扬中市| 济源市| 万州区| 博爱县| 沐川县| 昌邑市| 平潭县| 遂川县| 南昌县| 揭西县| 日喀则市| 鹿泉市| 贺兰县| 商水县| 呼玛县| 比如县| 南召县| 弥渡县| 二手房| 仁化县| 监利县| 沙洋县| 余庆县| 黔西县| 安西县| 琼结县| 铅山县| 西乌珠穆沁旗| 辰溪县| 平南县| 石门县| 贡嘎县| 吴旗县| 淮北市| 岳阳市| 金门县| 历史| 富蕴县| 和平县| 方山县| 三门峡市|