-2

What I want to do, is transform my variable:

table = "female\tIngelin\tAleksandersen\nmale\tJohnny\tDigre\nmale\tOsman\tBremseth\nfemale\tCathrine\tDagestad\nfemale\tTirill\tBakker"

Into a kind of scheme like this:

  1. Row: 0 Col: 0 Cell value: female
  2. Row: 0 Col: 1 Cell value: Ingelin
  3. Row: 0 Col: 2 Cell value: Aleksandersen
  4. Row: 1 Col: 0 Cell value: male
  5. Row: 1 Col: 1 Cell value: Johnny

The list is long, so ill stop at 5, but you get the point. My code so far:

table="female\tIngelin\tAleksandersen\nmale\tJohnny\tDigre\nmale\tOsman\tBremseth\nfemale\tCathrine\tDagestad\nfemale\tTirill\tBakker"

def show_table():
    print(table)

def show_every_cell():
    col = -1
    row = -1
    names = table.split("\t")
    for x in names:
        row += 1
        if row == 0:
            col += 1
            if col == 0:
                print('Row: 0 Col: 0 ' + 'Cell value: ' + x)
            if col == 1:
                print('Row: 0 Col: 1 ' + 'Cell value: ' + x)
            if col == 2:
                print('Row: 0 Col: 2 ' + 'Cell value: ' + x)

        if row == 1:
            col += 1
            if col == 0:
                print('Row: 1 Col: 0 ' + 'Cell value: ' + x)
            if col == 1:
                print('Row: 1 Col: 1 ' + 'Cell value: ' + x)
            if col == 2:
                print('Row: 1 Col: 2 ' + 'Cell value: ' + x)

    #The list continues with row: 2, 3 and 4. But no point in showing that part. 

def main():
    show_table()
    show_every_cell()

if __name__ == "__main__":
    main()

My output is this:

Row: 0 Col: 0 Cell value: female
Row: 1 Col: 1 Cell value: Ingelin

As you see, it misses quite a lot....

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
pythonstud
  • 41
  • 5

2 Answers2

2

Expanding my comment:

You never reset col before you print a new row. But this is a prime example for don't repeat yourself - instead of writing nearly identical code 4 times, why not use loops?

To reproduce your output, you could use this as a starting point:

for rowno, row in enumerate(table.split("\n")):
    for colno, cell in enumerate(row.split("\t")):
        print("Row: {}, Col: {}, Cell value: {}".format(rowno, colno, cell))

These are two nested loops, which iterate over the input while using enumerate to automatically count the respective position.

Notice that the split function is used twice: once to split on newlines (\n) to get each row, then to split on tabs (\t) for each cell.

Since this very much looks like a csv-file, also have a look at the csv-module.

Christian König
  • 3,437
  • 16
  • 28
0

You should try a nested for loop. ...

for x in names:
   for row in range(number_of_rows):
      for col in range(number_of_cols):
         print('Row: ' + row + 'Col: ' + col + 'Cell value: ' + x)
Jake
  • 617
  • 1
  • 6
  • 21