Doubt in string comparison and list value for all lines

Asked

Viewed 138 times

4

I have a table of 5 rows and 5 columns. For each column I have a name, for example: Name, Age, Gender, Weight, Height. And all cells 5*5 are filled.

I need the following formatting:

Idade
João - 15
José - 16
Maria - 21

Sexo
João - M
José - M
Maria - F

That is, for each cell information I need to show me which person this result is related to.

I already list the title (Age) and the value (16), but I can not link the name to each information, getting:

Nome
JOão
JOsé
MAria

Idade
16
15
21

Sexo
M
M
F

I created a variable by receiving the value of the cell(x,y), but prints empty. Follows my code:

   for crange in sheet.merged_cells:                
      rlo, rhi, clo, chi = crange                    
      rranges[(clo,rlo)] = rhi - rlo;
    for col_index in range(sheet.ncols):
      linhas = iter(range(sheet.nrows));             
      nome_mol = ""                                   

      for row_index in linhas:
        if (sheet.cell_value(row_index,col_index) != ''): 
          valor = sheet.cell_value(row_index,col_index);
          if (sheet.cell_value(row_index,col_index) == "NOME"): 
            nome_mol = sheet.cell_value(row_index,col_index)   

            print "{} -- {} |{} |".format(nome_mol, valor) 

1 answer

4


I am assuming that the first line contains the labels ("Name", "Age", ...) and the others contain data. If this is incorrect, please edit the question clarifying the fact.

As I understand it, the column with [people’s] names is the first column (index 0), right? So you need to iterate on the other (1 to ncols):

for col_index in range(1, sheet.ncols):
    print sheet.cell_value(0, col_index) # Imprime o nome da coluna

Similarly, the first row contains the names of the columns, so you need to iterate over the others:

    for row_index in range(1, sheet.nrows):

The person’s name will then be in the first column of the row, and the attribute in question ("Age", "Sex", ...) will be the crossing of the row with the column:

        nome = sheet.cell_value(row_index, 0)
        valor = sheet.cell_value(row_index, col_index)

These values need to be formatted and printed. In your code there is a {} leftover:

        print "{} - {}".format(nome, valor) # Imprime o nome da pessoa e seu atributo

Complete code:

for col_index in range(1, sheet.ncols):
    print sheet.cell_value(0, col_index) # Imprime o nome da coluna
    for row_index in range(1, sheet.nrows):
        nome = sheet.cell_value(row_index, 0)
        valor = sheet.cell_value(row_index, col_index)
        print "{} - {}".format(nome, valor) # Imprime o nome da pessoa e seu atributo
  • Thank you so much for the explanation, I hope I can get this logic as soon as possible. It worked. Thank you

Browser other questions tagged

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