DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world
Convert List Of List/tuple To List Of Object Named, Python
my version of "named tuple"
class OList:
"""
l=[("martin","jean"),("dupond","yves"),("klein","michel")]
or
l=[["martin","jean"],["dupond","yves"],["klein","michel"]]
ll = OList("nom","prenom")(l)
print ll[2].prenom,"==",ll[2][1],"==",l[2][1]
"""
def __init__(self,*a):
self.__n=list(a)
def __call__(self,liste):
class NList(list):
def __init__(self,n,l):
assert len(l)==len(n), "No match "+str(n)+" and "+str(l)
list.__init__(self,l)
for i in n:
setattr(self,i,l[ n.index(i) ])
self.__noms = n
def __repr__(self):
m=" ".join(["""%s='%s'""" % (i,str(getattr(self,i))) for i in self.__noms])
return "<objet %s>" % m
return [ NList(self.__n, i) for i in liste ]





