2016-07-28 70 views
0

所以,我有一個巨大的對象列表,其中包含:難度等級,數學表達式,結果。我試圖構建一個遊戲,並希望打印表達式並檢查結果,但我不知道如何打印單獨的元素。 我的列表是什麼樣子的: 3,s,520 + 370,890 我想只打印表達式: 類似於:print(list,key = lambda x:x.nivel) 但是隻有一個元素該名單E一個對象(在這種情況下NIVEL)的我如何使用對象列表中的單獨元素?

代碼:

class Expressao(object): 

    def __init__(self, nivel, tipo, expressao, resposta): 
     self.nivel = nivel 
     self.tipo = tipo 
     self.expressao = expressao 
     self.resposta = resposta 

    def __repr__(self): 
     return self.nivel + ", " + self.tipo + ", " + self.expressao + ", " + self.resposta` 

class FonteDeExpressoes(object): 
    import csv 
    def lista (self): 
     expressoes = [] 
     with open('exp.txt') as f: 
      for line in f: 
       row = line.split('\t') 
       exp = Expressao(row[0], row[1], row[2], row[3]) 
       expressoes.append(exp) 
     #print expressoes 
     return expressoes 
+1

請[edit]展示一個[mcve] –

+0

你有沒有嘗試過任何東西?發佈你的代碼示例,我們會盡力幫助你。如果沒有這部分內容,SO社區無法弄清楚你想完成什麼。你的代碼,你需要幫助.. – repzero

+0

@MosesKoledoye我得到這個錯誤: TypeError:'Expressao'對象不支持索引 –

回答

0

給出的列表expressoes,你可以使用map列表理解所包含的類實例的屬性:

list_of_nivels = map(lambda x: x.nivel, expressoes) 

在Python 3.x中,你將需要調用listmap返回一個列表

並配有理解:

list_of_nivels = [expressao.nivel for expressao in expressoes] 

要返回多個屬性從列表中的每個實例可以使用operator.attrgetter

import operator 

nivels_and_resposta = [operator.attrgetter('nivel', 'resposta')(x) for x in expressoes] 
+0

這解決了我的問題!但是我的列表返回如下所示:('3','82 \ r \ n')我理解\ n換行符而不是\ r。 –

+0

@AlexandrePrecrecal這是一個回車。有些系統通常將EOL字符指定爲''\ r \ n' –

相關問題