how to code linked list in python with multiple variables -


i kind of new python. background more in java , c++. i'm trying create linked list multiple variables. know can done in java , c++ im not sure how set python. have code have found on other websites work single variable need hold several pieces of information. have is:

 class node:      def __init__(self, cargo=none, next=none):          self.cargo = cargo          self.next  = next       def __str__(self):          return str(self.cargo) 

this ok need more info this. c++ put many variables wanted in struct. can please advise on need change can use many pieces of data. example: movie title, rating, genre, ect. (not project example). goal of project to compare 2 very large list each other. or maybe has more efficient way of doing this. love hear it.

thanks in advance

python uses called 'duck typing'. if object walks duck , quacks duck, it's duck. think of 'walk' , 'quack' object methods. long methods exist on object, can called. cargo can long of methods call exist on it.

a java analogy might if imagine node.cargo base object class, , somewhere else in code might explicitly cast before calling method. if cast fails, exception. difference python don't cast before calling method, , instead checks see whether method exists on object (that is, walk duck).

so in example, if set bunch of nodes support len() function, , iterate on nodes, fine:

node3 = node('last') node2 = node(['m', 'i', 'd'], node3) node1 = node(('fir', 'st'), node2)  def visit_all(node):     while node:          print(type(node.cargo), node, len(node.cargo))          node = node.next  >>> visit_all(node1)  <class 'tuple'> ('fir', 'st') 2  <class 'list'> ['m', 'i', 'd'] 3  <class 'str'> last 4 

however, if try pass in node doesn't support len(), exception, similar java classcastexception.

node0 = node(0, node1)  >>> visit_all(node0)  typeerror: object of type 'int' has no len() 

so of said, if want group movie title, rating, genre, etc. store in separate class, , not inside node. if grouped data immutable, @ using namedtuple. again, think of cargo java object don't have explicitly cast before calling methods or properties.

edit: op requested explicit example of having node store custom class.

class movie(object):     def __init__(self, title, rating, actors):         self.title = title         self.director = director         self.actors = actors  node = node('some movie', 'pg', ('john doe', 'jane doe'))  >>> print(node.cargo.title)  movie 

or if movie class can immutable:

from collections import namedtuple  movie = namedtuple('movie', ['title', 'rating', 'actors']) node = node('some movie', 'pg', ('john doe', 'jane doe'))  >>> print(node.cargo.rating)  pg 

Comments

Popular posts from this blog

php - regexp cyrillic filename not matches -

c# - OpenXML hanging while writing elements -

sql - Select Query has unexpected multiple records (MS Access) -