網站首頁 編程語言 正文
源碼解釋:
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)
"""
語法結構:
namedtuple(typename, field_names, *, rename=False, defaults=None, module=None)
- typename: 代表新建的一個元組的名字。
- field_names: 是元組的內容,是一個類似list的[‘x’,‘y’]
命名元組,使得元組可像列表一樣使用key訪問(同時可以使用索引訪問)。
collections.namedtuple 是一個工廠函數,它可以用來構建一個帶字段名的元組和一個有名字的類.
創建一個具名元組需要兩個參數,一個是類名,另一個是類的各個字段的名字。
存放在對應字段里的數據要以一串參數的形式傳入到構造函數中(注意,元組的構造函數卻只接受單一的可迭代對象)。
命名元組還有一些自己專有的屬性。最有用的:類屬性_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類,有lat/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 的形式返回,可以利用它來把元組里的信息友好地呈現出來。
print(delhi._asdict())
運行結果:
示例代碼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)
運行結果:
示例代碼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)
# 根據索引取值
def __getitem__(self, item):
return self._cards[item]
f = FrenchDeck()
print(f.__len__())
print(f.__getitem__(3))
運行結果:
示例代碼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]))
運行結果:
示例代碼5:? ?【_make 從存在的序列或迭代創建實例】
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)
運行結果:
示例代碼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())
運行結果:
示例代碼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)
運行結果:
示例代碼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)
運行結果:
示例代碼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)
運行結果:
示例代碼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'))
運行結果:
示例代碼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)
運行結果:
示例代碼12:? ?【注意觀察兩種寫法的不同】
from collections import namedtuple
Point = namedtuple("Point", ["x", "y"])
p = Point(11, 22)
print(p)
print(p.x, p.y)
# namedtuple本質上等于下面寫法
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)
運行結果:
原文鏈接:https://blog.csdn.net/weixin_44799217/article/details/126594612
相關推薦
- 2022-10-11 Spring Boot 使用@Scheduled注解實現定時任務
- 2022-02-18 引入redis報錯Bean method ‘redisConnectionFactory‘ not
- 2022-03-31 python中常用的九個語法技巧_python
- 2022-07-10 jQuery表格添加數據并Ajax提交數據
- 2022-11-17 Android使用元數據實現配置信息的傳遞方法詳細介紹_Android
- 2022-09-18 iOS開發探索多線程GCD隊列示例詳解_IOS
- 2021-12-16 .NET中的狀態機庫Stateless的操作流程_實用技巧
- 2023-07-27 原型和原型鏈條、ES6、前后端交互Ajax
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支