python - 将dict添加到for循环中的列表
问题描述
根据我的调试器和我的 25 行测试 csv,该patient_appts
列表包含预期的 25 个字典。我似乎无法弄清楚该列表是如何None
在局部变量、返回语句和主函数之间形成的。
我已经在几个地方读到了您需要制作副本而不是附加参考,据我所知,我已经这样做了,使用 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()
解决方案
您在函数中有一个随机return
语句run_CSV
,当您点击该函数时,您的函数什么也不返回 -None
当您的main
功能尝试执行此操作len
时,None
您将收到该错误。由于这是循环的一部分,我猜你打算在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
推荐阅读
- java - spring-message依赖连接问题
- php - 使用 JMS 3.11 反序列化时,setSerializeNull() 报告为未定义
- azure-service-fabric - 启用 gMSA 时如何设置安全服务结构仪表板?
- python - 如何在 Huggingface + CUDA 内存不足的 BERT 之上添加 BiLSTM。尝试分配 16.00 MiB
- java - 用斜杠替换文字的 Java 把手
- python - Django 模型如何修复循环导入错误?
- c - C 指向数据。为什么显示错误;二进制的无效操作数?
- c - 将 char* 复制到 char* 的指针
- android - Android错误膨胀类
加载高图时 - css - 如何在溢出设置为可见时显示线性渐变的边框半径 - React Native IOS