我想要实现的是一个 csv 文件,如下所示:
,h.r9,h.r8,h.r5,h.r4,h.r7,h.r6,h.r1,h.r3,h.r2,h.r10
chris,0,1,0,0,0,0,0,1,0,0
bob,0,0,1,1,1,1,0,0,0,1
dick,1,0,1,0,0,0,0,0,1,1
ab,1,2,0,0,0,0,0,0,0,0
emma,0,0,1,0,1,0,1,0,1,0
有点不相关:有谁知道这样的矩阵的实际名称是什么?这至少会使谷歌搜索这个问题更容易。
数据最初在这样的字典中:
dict = {}
dict['ab'] = ["h.r1","h.r2"]
dict['bob'] = ["h.r3","h.r4","h.r5","h.r6","h.r10"]
dict['chris'] = ["h.r2","h.r8"]
dict['dick'] = ["h.r1","h.r10","h.r9","h.r3"]
dict['emma'] = ["h.r3","h.r5","h.r7","h.r9"]
因此,如果一个人在字典中有变量,则 CSV 中应该是 1,否则应该是零。
下面的代码构建 csv 文件,但全为零。我将如何实现 1 和 0 的逻辑?我可以在 PHP/HTML 中做到这一点,但是对于 Python 来说非常陌生,我并没有赶上......还有一个库可能已经内置了这个函数吗?(也许是numpy?)
import csv
dict = {}
dict['ab'] = ["h.r1","h.r2"]
dict['bob'] = ["h.r3","h.r4","h.r5","h.r6","h.r10"]
dict['chris'] = ["h.r2","h.r8"]
dict['dick'] = ["h.r1","h.r10","h.r9","h.r3"]
dict['emma'] = ["h.r3","h.r5","h.r7","h.r9"]
mergedlist = []
for k,v in dict.items():
mergedlist = mergedlist + v
mergedlist = list(set(mergedlist))
listlen = len(mergedlist)
mergedlist[0:0] = " "
thekeys = []
for k in dict.keys():
thekeys.append(k)
thecsv = csv.writer(open("your.csv", 'w', newline=''))
thecsv.writerow(mergedlist)
for col in thekeys:
thecsv.writerow([col] + ['0']*listlen) #does the logic go in here somehow??