Alexandre Pedrecal Alexandre Pedrecal - 4 months ago 9
Python Question

How can i work with separate elements in a list of objects?

So, i have a huge list of objects which contains: Level Of Difficulty, Math Expression, Result. I'm trying to build a game and want to print the expression and check the result, but i don't know how to print a separate element.
What my list looks like:
3, s, 520 + 370, 890
I want to print only the expression:
Something like: print(list, key=lambda x: x.nivel)
But only one of the elements of the list e one object(nivel in this case)

Code:

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

Answer

Given the list expressoes, you can get the attributes of the contained class instances using map or a list comprehension:

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

In Python 3.x, you'll need to call list on map to return a list

And with a comprehension:

list_of_nivels = [expressao.nivel for expressao in expressoes]

To return more than one attribute from every instance in the list, you can use operator.attrgetter:

import operator

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