csv.dictreader文件不提供所需的输出

2024-04-20 10:25:38 发布

您现在位置:Python中文网/ 问答频道 /正文

圣诞快乐!你知道吗

我有以下数据:

a = ("   101,   151,     0,'T1',2,2,1, 1.71470E-1,-1.02880E-1,2,'NUCA GSU    ',1,   1,0.3200,   2,0.3900,   3,0.1400,   4,0.1500",
 "1.10000E-3, 9.10000E-2,  1200.00",
"21.6000,  21.600,   0.000,  1200.00,  1100.00,  1000.00, 1,    101,22.68000,20.52000, 1.05000, 0.95000,  25, 0, 0.00021, 0.00051",
"500.000, 500.000")

b = (('I','J','K','CKT','CW','CZ','CM','MAG1','MAG2','NMETR','NAME',
             'STAT','O1','F1','O2','F2','O3','F3','O4','F4'),
            ('R1-2','X1-2','SBASE1-2'),
            ('WINDV1','NOMV1','ANG1','RATA1','RATB1','RATC1','COD1','CONT1',
             'RMA1','RMI1','VMA1','VMI1','NTP1','TAB1','CR1','CX1'),
            ('WINDV2','NOMV2'))

我想写一份口述如下:

{'I': 101, 'J': 151, ...... 'F4': 0.1500}
{'R1-2': 1.10000E-3, ...... 'SBASE1-2': 1200.0}
{'WINDV1': 21.60, ...... 'ÇX1': 0.00051}
{'WINDV2': 500.0, 'NOMV2': 500.0}

我想用csv.DIC阅读器所以我尝试了以下代码:

for j in range(4):
    c=list(csv.DictReader(a[j], fieldnames=b[j]))
    print c

我没有得到期望的输出。我做错什么了?你知道吗

我已经可以这样做了:

for j in range(4):
    c=dict(zip( b[j], (a[j].split(','))))
    print c

Tags: csv数据inforranget1printx1
1条回答
网友
1楼 · 发布于 2024-04-20 10:25:38

我认为不做这件事更简单csv.DictReader文件,您没有读取CSV。你知道吗

newListOfDict=[]
for keyLine, valueLine in zip(b, a): #one and one line from a and b
    #the string line in b splitted and stripped
    splittedValues = map(lambda v: v.strip(), valueLine.split(","))
    #create the new dict with the result of zip : ((b1, a1),(b2, a2)...)
    newDict = dict(zip(keyLine, splittedValues))
    newListOfDict.append(newDict)
print newListOfDict

相关问题 更多 >