Pythonで線形リスト

標準の型で入っててくれたら便利なのにー
以前も書いた気がしますけれども ちょっと必要になったので Pythonで線形リスト (Consリスト)を書いてメモ


from collections.abc import Iterable
class Cons( object ):
def __init__(self,left,right):
self.left=left
self.right=right
def __iter__(self):
if isinstance(self.left,Cons):
l= tuple(self.left.__iter__())
else:
l= self.left
yield l
if isinstance(self.right,Cons):
for i in self.right:
yield i
elif self.right is None:
raise StopIteration
else:
yield self.right

def __str__(self):
return str(tuple(iter(self)))

class ConsList(Cons):
def __init__(self, itr):
self.left=None
self.right=None
left=itr[0]
if isinstance(left,Iterable):
self.left=ConsList(left)
else:
self.left=left
right=itr[1:]
if len(right)>0:
self.right=ConsList(right)
else:
self.right=None

if __name__=="__main__":
c=ConsList( [[1,2,3],[4,5,6],[7,8,9]])
print(c)
c=ConsList(range(15))
print(c)
c=ConsList([1,2,3])
assert c.right.right.right is None
assert list(c)==[1, 2, 3]
print("done")