1
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?

1 Answer 1

1

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())
Sign up to request clarification or add additional context in comments.

3 Comments

do you mean cds.append(CD(i ,title ,author)) ?
It gives me a UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 4903: ordinal not in range(128) What does this mean?
@joe Maybe try open('CDs.txt', encoding='utf-8') instead?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.