joe
joe

Reputation: 161

How to create a data structure in a Python class

class CD(object):
        def __init__(self,id,name,singer):
                self._id = id
                self.n = name
                self.s = singer

        def get_info(self):
                info = 'self._id'+':'+ ' self.n' +' self.s'
                return info

class collection(object):
        def __init__(self):
                cdfile = read('CDs.txt','r')

I have a file 'CDs.txt' which has a list of tuples look like this:

[
("Shape of you", "Ed Sheeran"),
("Shape of you", "Ed Sheeran"),
("I don't wanna live forever", "Zayn/Taylor Swift"),
("Fake Love", "Drake"),
("Starboy", "The Weeknd"),

......
]

Now in my collection class, I want to create a CD object for each tuple in my list and save them in a data structure. I want each tuple to have a unique id number, it doesn't matter they are the same, they need to have different id....can anyone help me with this?

Upvotes: 1

Views: 85

Answers (1)

Franz Wexler
Franz Wexler

Reputation: 1252

You can use simple loop with enumerate for this.

# I don't know what you mean by 'file has list of tuples',
# so I assume you loaded it somehow
tuples = [("Shape of you", "Ed Sheeran"), ("Shape of you", "Ed Sheeran"),
          ("I don't wanna live forever", "Zayn/Taylor Swift"),
          ("Fake Love", "Drake"), ("Starboy", "The Weeknd")]

cds = []
for i, (title, author) in enumerate(tuples):
    cds.append(CD(i, title, author))

Now you have all CDs in a nice, clean list

If your file is just the list in form [('title', 'author')], then you can load it simply by evaluating its contents:

tuples = eval(open('CDs.txt').read())

Upvotes: 1

Related Questions