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?
jww
104k107 gold badges454 silver badges975 bronze badges
1 Answer 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())
answered Feb 26, 2017 at 16:54
Franz Wexler
1,2622 gold badges10 silver badges15 bronze badges
Sign up to request clarification or add additional context in comments.
3 Comments
joe
do you mean cds.append(CD(i ,title ,author)) ?
joe
It gives me a UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 4903: ordinal not in range(128) What does this mean?
Franz Wexler
@joe Maybe try
open('CDs.txt', encoding='utf-8') instead?lang-py