如何迭代并编写列表作为 CSV header?

How to iterate and write a list as the CSV header?

我有一个用例,我按如下方式从 SPARQL 端点提取数据:

SPARQL = SPARQLWrapper(endpointURL)  
SPARQL.setQuery(queryString) 
SPARQL.setReturnFormat(JSON) 
results = SPARQL.query().convert() 

'results' 变量保存我现在要写入 CSV 文件的数据。首先,我为 CSV 创建了 header,如下所示:

schema = ['Age', 'Sex', 'Chest_Pain_Type', 'Trestbps', 'Chol', 'Fasting_Glucose_Level', 'Resting_ECG_Type', 'ThalachD', 'Exercise_Induced_Angina', 'OldpeakD', 'CaD', 'Slope', 'Thallium_Scintigraphy', 'Diagnosis']

然后我使用以下代码将每一行的数据写入 CSV 文件中:

with open('DIC.csv', 'w+') as csvfile: 
        writer = csv.writer(csvfile, delimiter=',') 
        writer.writerow([g for g in schema]) 
        for result in results["results"]["bindings"]: 
                    writer.writerow([result["Age"]["value"], 
                    result["SexTypes"]["value"],
                    result["Chest_Pain_Type"]["value"], 
                    result["trestbpsD"]["value"],
                    result["cholD"]["value"], 
                    result["Fasting_Glucose_Level"]["value"],
                    result["Resting_ECG_Type"]["value"],
                    result["thalachD"]["value"],
                    result["Exercise_Induced_Angina"]["value"],
                    result["oldpeakD"]["value"],
                    result["caD"]["value"],
                    result["Slope"]["value"],
                    result["Thallium_Scintigraphy"]["value"],
                    result["Diagnosis"]["value"]])
        file_name = csvfile.name
        csvfile.close()

在前面的代码块中,result["SexTypes"]["value"]用于写入值(即"value")列 "SexTypes"。这意味着,第一个索引是可变的,但第二个索引始终相同。

虽然,上面的代码工作正常,但这几乎是 hard-coded,一旦我的 SPARQL 查询发生变化(即,如果架构不同),它就会失败。

我现在想让它更灵活,以便我迭代列表中的所有列,但 "value" 是固定的。为此,我尝试了以下代码,但最终失败了:

with open('DIC.csv', 'w+') as csvfile: 
        writer = csv.writer(csvfile, delimiter=',') 
        writer.writerow([g for g in schema]) 
        r = "value"
        for result in results["results"]["bindings"]: 
            for i in range(len(schema)):
                writer.writerow([result[schema[i]][r]])
                i = i + 1       
        file_name = csvfile.name
        csvfile.close()
        return file_name

我知道,我做错了什么。请问有什么更好的建议吗?

[也许这个问题值得一个更好的标题,但我找不到。不过,抱歉我的英语不好。]

第一个示例代码中 writer.writerow() 的输入是一个列表,长度与 schema 相同,而第二个示例代码中它是一个长度为 1 的列表(而不是调用 writerow() 调用一次是 schema 中的每个元素一次。

要生成您最初拥有的列表,您可以使用列表理解来完成:

row = [result[column]["value"] for column in schema]

相当于:

row = [] # create empty list
for column in schema:
    row.append(result[column]["value"])

最终,代码只需要在 results:

循环内修改
...
for result in results["results"]["bindings"]: 
    row = [result[column]["value"] for column in schema]
    writer.writerow(row)
file_name = csvfile.name
...