我一直在尝试将xml文件转换为CSV文件格式。 现在我有一个小问题。哪个是将其打印到csv文件中的if else语句。
这就是我所拥有的
我有一张20的len字典。
Rankings{4706: '8.185', 2358: '0.444', 6245: '0.851', 615: '0.444', 7626: '2.164', 2219: '0.315', 4338: '0.348', 3790: '0.876', 6194: '0.362', 2228: '0.541', 597: '0.495', 6838: '3.883', 4567: '1.173', 7800: '0.521', 3796: '0.326', 2042: '5.076', 5141: '0.316', 1722: '0.595', 5566: '0.555', 1429: '0.435'}
我有几个7804大的名单。
eventIDList = []
artKeyList = []
languageAll = []
startDateTime = []
endDateTime = []
sentenceID = []
sentenceContent = []
我使用dictionaryKey与eventIDList进行比较,这样如果它相同,它会将密钥的值打印到csv文件中。
所以我尝试使用
for a in rankings:
for i in range(7804):
if(int(a) == int(eventIDList[i])):
csvFile.write(eventIDList[i] + ',' + ...... +',' + rankings[a])
else:
csvFile.write(eventIDList[i] + ',' + ..... + ',' + " "(rankings) + ',' + sentenceContent[i])
问题是程序只通过if语句。但是我仍然需要通过else语句。
我的代码中哪处出错了?
答案 0 :(得分:0)
如果所有数组都具有相同的长度,并且您的输出必须是每个数组位置的一行,那么您的循环应该如下所示
eventIDList = range(7804)
sentenceContent = range(7804)
rankings = {4706: '8.185', 2358: '0.444', 6245: '0.851', 615: '0.444', 7626: '2.164', 2219: '0.315', 4338: '0.348', 3790: '0.876', 6194: '0.362', 2228: '0.541', 597: '0.495', 6838: '3.883', 4567: '1.173', 7800: '0.521', 3796: '0.326', 2042: '5.076', 5141: '0.316', 1722: '0.595', 5566: '0.555', 1429: '0.435'}
for idx in range(len(eventIDList)):
if rankings.get(idx,'') and eventIDList[idx] == rankings.get(idx,''):
csvFile.write( "%i, %s" % (eventIDList[idx] , rankings[idx]))
else:
csvFile.write( "%i, %i" % (eventIDList[idx] , sentenceContent[idx]))