簡體   English   中英

如何使我的多個 if 語句起作用? 或者最好如何在我的代碼中使用嵌套循環

[英]How can I make my multiple if statements work? Or preferably how do I use nested loops in my code

我想做的是轉換我的變量:

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

變成這樣的一種方案:

  1. 行:0 列:0 單元格值:女性
  2. 行:0 列:1 單元格值:Ingelin
  3. 行:0 列:2 單元格值:Aleksandersen
  4. 行:1 列:0 單元格值:男性
  5. 行:1 列:1 單元格值:Johnny

名單很長,所以我會停在 5 點,但你明白了。 到目前為止我的代碼:

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()

我的輸出是這樣的:

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

如您所見,它錯過了很多......

擴大我的評論:

在打印新行之前,您永遠不會重置 col。 但這是一個最好的例子,不要重復自己 - 與其編寫幾乎相同的代碼 4 次,為什么不使用循環?

要重現您的輸出,您可以使用它作為起點:

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))

這是兩個嵌套循環,它們在使用enumerate自動計算相應位置的同時迭代輸入。

請注意,split函數使用了兩次:一次在換行符 ( \\n ) 上拆分以獲取每一行,然后在每個單元格的制表符 ( \\t ) 上拆分。

由於這看起來很像一個 csv 文件,所以也看看csv-module

您應該嘗試嵌套for循環。 ...

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM