2017-02-26 43 views
0
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') 

我有一個文件「CDs.txt」其中有一個元組列表創建一個數據結構是這樣的:如何在Python類

[ 
("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"), 

...... 
] 

現在在我的集合類,我想爲列表中的每個元組創建一個CD對象,並將它們保存在數據結構中。我希望每個元組都有一個唯一的ID號,無所謂他們是一樣的,他們需要有不同的ID ....任何人都可以幫助我呢?

回答

1

您可以使用簡單的循環與enumerate爲此。

# 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)) 

現在你把所有的CD在一個不錯的,乾淨的列表

如果你的文件只是在形式上[('title', 'author')]列表中,那麼你可以簡單地通過評估其內容加載:

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

你的意思是cds.append(CD(我,標題,作者))? – joe

+0

@joe是的,我更正了代碼 –

+0

它給了我一個UnicodeDecodeError:'ascii'編解碼器無法解碼位置4903中的字節0xc3:序號不在範圍內(128)這是什麼意思? – joe