How to use Join in an object list?

Asked

Viewed 139 times

0

class Pessoa:
      def __init__(self, nome, idade):
          self.nome = nome
          self.idade = idade

p1 = Pessoa('João', 15)  
p2 = Pessoa('Maria', 17)
lista_pessoas = [p1, p2]

How to use the join() to print the list of names, or the list of ages without having to create another list?

  • You need a string only with all names or all ages?

  • What you want to do, is not clear in the question

1 answer

4

Since you already have a list of people, you can use the function map:

class Pessoa:
      def __init__(self, nome, idade):
          self.nome = nome
          self.idade = idade

p1 = Pessoa('João', 15)  
p2 = Pessoa('Maria', 17)
lista_pessoas = [p1, p2]
nomes = ', '.join(map(lambda p: p.nome, lista_pessoas))
print(nomes)

The first parameter passed to map is a lambda: a function that will be applied to each item in the list. In this case, the lambda receives a person and returns their respective name, and does so for each element of the list.

The detail is that the function map returns a iterator. That is, she does not create another list.

Then we use join to join the names, separating them by ', ' (comma and a space). The result is:

João, Maria

If you want to show the ages, just change the lambda for:

idades = ', '.join(map(lambda p: str(p.idade), lista_pessoas))

But how idade is a number, we have to use str to convert it to string. At the end, the string idades will have the value 15, 17.


Another alternative is to use what was suggested in the comments:

nomes = ', '.join(p.nome for p in lista_pessoas)

This code uses the syntax of comprehensilist on, much more succinct and pythonic. And besides, she creates a Generator (that is, it also does not create another list).

For ages, I’d stay:

idades = ', '.join(str(p.idade) for p in lista_pessoas)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.