【问题标题】:If Loop in Python Stopped working, using jupyter?如果 Python 中的循环停止工作,使用 jupyter?
【发布时间】:2020-10-31 12:22:29
【问题描述】:

我正在导入 CSV 文件并导入数据。在代码中,if 循环 (if get_id == 1 :) 停止工作。当我第一次写它时,它正在工作。我做了一些分析,但我认为该循环没有运行。我写的对吗?

在 CSV 中,第一列有几个 ID。

confirmed_array=[]
total_array=[]
dates_array=[]

with open('dataset1.csv') as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')
    csv_writer = csv.writer(csv_file, delimiter=',')
    
    print('File has been imported')
    csv_headings = next(csv_reader)
    
    Cumlative_Cases_Total=0
    Cumlative_Cases_Confirmed=0 
    probabal=0 
    
    test=0
    tracker=0

     #cleaning data    
  
    for line in csv_reader:
        for i, x in enumerate(line):
            if len(x)< 1:
                         x = line[i] = 0
    
    for line in csv_reader:
        
        get_id=int(line[0])
        
        new_case=int(line[4])
        prob=int(line[5])
        deaths=int(line[6])
        recovered=int(line[9])
        today_case=int(line[12])
        
       
        if get_id == 1 :
            probabal=probabal+prob
        
            Cumlative_Cases_Total = Cumlative_Cases_Total + today_case + prob
            Cumlative_Cases_Confirmed=Cumlative_Cases_Confirmed+today_case-probbabal
            
            print('')
           
            confirmed_array.append(Cumlative_Cases_Confirmed)
            total_array.append(Cumlative_Cases_Total)
            
            tracker= tracker+1
            
          

【问题讨论】:

  • 您是否尝试过在每次迭代时打印 get_id 以检查它是否真的执行过 == 1?
  • 你怎么知道它没有运行?
  • 就像注释一样,没有 if 循环之类的东西。应该是 if 语句。
  • @deadshot 数组最初是空的。我在 if 语句中添加了它们。当它运行时,数组是空的。我将一些打印语句放在不同的位置,并注意到 if 语句被跳过了
  • @KelVarnsen 感谢您的收获!注意到

标签: python csv for-loop jupyter-notebook


【解决方案1】:

我想通了(我想)

问题似乎出在这部分

        for i, x in enumerate(line):
            if len(x)< 1:
                         x = line[i] = 0

当代码运行时,这会使行走到最后。因此,当它进入下一个部分时,该部分将被跳过。相反,我编写了这样的代码:

confirmed_array=[]
total_array=[]
dates_array=[]

with open('dataset1.csv') as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')
    csv_writer = csv.writer(csv_file, delimiter=',')
    
    print('File has been imported')
    csv_headings = next(csv_reader)
    
    Cumlative_Cases_Total=0
    Cumlative_Cases_Confirmed=0 
    probabal=0 
    
    test=0
    tracker=0

    
    for line in csv_reader:
        
        for i, x in enumerate(line):
            if len(x)< 1:
                         x = line[i] = 0
        
        get_id=int(line[0])
        
        new_case=int(line[4])
        prob=int(line[5])
        deaths=int(line[6])
        recovered=int(line[9])
        today_case=int(line[12])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-23
    • 1970-01-01
    相关资源
    最近更新 更多