【问题标题】:Adding dict to list within for-loop将dict添加到for循环中的列表
【发布时间】:2018-06-11 18:55:12
【问题描述】:

根据我的调试器和我的 25 行测试 csv,patient_appts 列表包含预期的 25 个字典。我似乎无法弄清楚该列表是如何在局部变量、return 语句和主函数之间变成 None 的。

我在几个地方读到了you need to make a copy 而不是附加引用,据我所知,我使用patient_appts.append(entry.copy()) 完成了这项工作

对不起,如果代码有点像火车事故,我对此很陌生,并试图自动化一些工作 - 例如,我很确定我不应该为我的数据手动创建 json 格式,但那是超出了这个问题的范围。

我尝试过全局实例化列表,而不是在函数内,全局并在函数内声明全局,在 with ed as ed_file: 之后实例化列表;他们似乎都产生了相同的结果(print(len(appointments))):

发生了异常。 TypeError,“NoneType”类型的对象没有 len()

调试器清楚地显示列表中的字典,然后再将其发送到return

import csv
from datetime import datetime, timedelta
from validate_email import validate_email
from fieldMap import fieldMap

record_count = 0
valid_email_count = 0



def run_CSV(ed):
    with ed as ed_file:
        global record_count
        global valid_email_count
        patient_appts = []
        header_row = True
        ed_reader = csv.reader(ed_file, delimiter=',', quotechar='"')

        for row in ed_reader:
            if not row[0] and not row[1]:
                print('\n%i records written to csv' % record_count
                      + '\n%i valid emails found' % valid_email_count)
                return
            elif header_row:
                headers = list(row)
                i_fname = headers.index(fieldMap['FirstName'])
                i_mname = headers.index(fieldMap['MiddleName'])
                i_lname = headers.index(fieldMap['LastName'])
                i_email = headers.index(fieldMap['Email'])
                i_start = headers.index(fieldMap['StartTime'])
                i_end = headers.index(fieldMap['EndTime'])
                i_location = headers.index(fieldMap['Location'])
                i_type = headers.index(fieldMap['Type'])
                i_appt_id = headers.index(fieldMap['ApptID'])
                header_row = False
            else:
                duration = getDuration(row[i_start], row[i_end])
                start_time = row[i_start]
                end_time = row[i_end]
                valid_email = validate_email(row[i_email])

                if valid_email:
                    valid_email_count += 1
                record_count += 1

                entry = {
                    'ApptID': row[i_appt_id],
                    'Data': {
                        'Patient': {
                            'FirstName': row[i_fname],
                            'MiddleName': row[i_mname],
                            'LastName': row[i_lname],
                            'Email': row[i_email],
                            'Valid Email': valid_email,
                            'Appointment': {
                                'Type': row[i_type],
                                'Location': row[i_location],
                                'StartTime': start_time,
                                'EndTime': end_time,
                                'Duration': duration
                            }
                        }
                    }
                }
                patient_appts.append(entry.copy())
        return patient_appts

def getDuration(start_time, end_time):
    fmt = '%I:%M %p'
    tdelta = datetime.strptime(
        end_time, fmt) - datetime.strptime(start_time, fmt)
    duration = str(tdelta).split(':')[1]
    return duration


def main():
    appointments = run_CSV(open(input('Enter full CSV Path:\n'), newline='\n'))
    print(len(appointments))

if __name__ == '__main__':
    main()

【问题讨论】:

  • 好吧,首先,您的if not row[0] and not row[1]: 上只有一个return
  • 至于需要附加副本的一点 - 这与您的情况无关,因为您每次都在构建一个新的entry。如果您创建对同一对象的多个引用的列表,例如 some_list = [{}] * 10some_dict = {}; some_list = []; for i in range(10): some_list.append(some_dict),则会导致令人惊讶的错误。

标签: python python-3.x list dictionary


【解决方案1】:

您在 run_CSV 函数中有一个随机的 return 语句,当您点击该语句时,您的函数什么也不返回 - None

当您的main 函数尝试在该None 上执行len 时,您将收到该错误。由于这是循环的一部分,我猜你打算在那里使用 break 而不是 return

应该是这样的:

    for row in ed_reader:
        if not row[0] and not row[1]:
            print('\n%i records written to csv' % record_count
                  + '\n%i valid emails found' % valid_email_count)
            break # formerly "return" was here

【讨论】:

  • 天哪,我不能(阅读:绝对可以)相信它是如此简单。
  • @JaredT 发生在我们最好的人身上 :)
猜你喜欢
  • 2018-04-06
  • 1970-01-01
  • 2013-05-28
  • 2020-03-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-09
  • 2015-11-28
相关资源
最近更新 更多