一個很省內存的工具,其基礎類型是tuple
namedtuple:
線程安全,可哈希,元組不可修改哦~(非絕對)
example:
Userprofile = ("Userprofile","name,email,user_id") # 1
Userprofile = ("Userprofile","name email user_id") # 1
Userprofile = ("Userprofile",["name","email","user_id"]) # 1
#三種傳遞方式都是可以的!
User_Info_tuple = ("Trump","[email protected]")
User_info_dict = {"name":"Trump","email":"[email protected]"}
#只要是iterable 都是可以通過_make()傳遞的
Userprofile._make(User_Info_tuple) #傳遞一個iterable !
Userprofile._make(User_dict_tuple)
# obj._asdict() 將裏面的數據dict化,返回的是OrderedDict類型!
Userprofile._asdict()
#如何處理多個數據? 個人感覺namedtuple在處理大量數據方面比較弱
from collections import namedtuple p_info = [{"name":"Trump","age":74}, {"name":"Baden","age":82}, {"name":"Sleep boy","age":83}, {"name":"Dolly","age":29} ] person = namedtuple("person",["A"+str(i) for i in range(0,len(p_info))]) # 動態生成key! 可以修改,我能想到的方法就只有這個了~~~ p = person(*p_info) print(p.A0.get("name")) #這裏會有點不兼容,Pycharm會顯示高亮,不可取~
# 比如我想要比較我的p_info裏面的數據那個不同,如果單單是用循環的話,那麼程序的內存消耗會很喫緊的! 所以我就想着用namedtuple試試,結果還是很不錯的~