Rescue only 10 first Python object records

Asked

Viewed 482 times

5

I am wrapped in a piece of code that I am doing. I need to rescue only the first 10 records of an object that I call into a for loop:

listaTabela = []
        for aluno in alunos:
            listaLinha = ""
            listaLinha += str(aluno.getRA())
            listaLinha += ";"
            listaLinha += str(aluno.getNome())

            listaTabela.append(listaLinha)

The way it is, it makes the loop normal as long as there are records on 'students'. Would there be a way to limit this loop so that it only runs on the first 10 records? I tried using while but he repeated the same record 10 times.

  • Sergio, if you can correct the indentation...

3 answers

9


You can just slice your student list like this:

listaTabela = []

for aluno in alunos[:10]:
    listaLinha = ""
    listaLinha += str(aluno.getRA())
    listaLinha += ";"
    listaLinha += str(aluno.getNome())

    listaTabela.append(listaLinha)
  • 1

    Thank you very much Thiago, that’s what I wanted! I looked for this type of manipulation but did not find in other places, thank you very much!

  • 1

    Thank you Jjoao. Corrected.

6

In your specific example, using the syntax indicated by @Thiagoluizs is the best alternative. I would just like to point out that not all eternal objects are "wearable". For example, this can be iterated:

for i in map(int, '12345'):
    print(i)

But it can’t be sliced:

map(int, '12345')[1:] # TypeError: 'map' object is not subscriptable

For these objects, use the itertools.islice.

from itertools import islice
for i in islice(map(int, '12345'), 1, 5):
    print(i)
  • Cool (+1). Alternatively list(map(int, '12345'))[1:]

2

If your Python is recent, try using lists in comprehension and f-strings:

tab=[f'Nome: {x.getNome()}; {x.getRA()}' for x in alunos[:10]]

Browser other questions tagged

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