首页 > 解决方案 > 如何修复 code_to_names

问题描述

我正在尝试编写一个函数 code_to_names,它接受一个 int 犯罪代码并返回一个字符串列表,其中每个字符串都包含犯罪的代码扩展名和全名。

现在,它正在输出整个列表而不是特定列表。我该如何解决?

import csv

def code_to_names(code):
    names = []
    with open('offense_codes.csv') as csv_file:
        reader = csv.reader(csv_file, delimiter=',')
        next(reader)  # skip the first row
        for row in reader:
            names.append(line)
    return names

code_to_names(2399) ['0:盗窃 - 其他','1:自行车盗窃','2:无偿驾驶盗窃燃料','3:电缆服务盗窃','4:建筑设备盗窃' , '5: 拖车失窃'] code_to_names(5707) ['0: 非法侵入']

标签: pythonpython-3.x

解决方案


要打开该文件,您可以提供文件的完整路径,例如。C:\Users\Desktop\offense_codes.csv 或使用os模块将您当前的工作目录更改为桌面,例如。 os.chdir(r'C:\Users\Desktop')

要启动其中一个功能,您需要调用其中一个,例如:code_to_names()

我建议你阅读 Al Sweigert 的“Automate the Boring Stuff with Python”。它非常适合初学者并且完全免费https://automatetheboringstuff.com/


推荐阅读