本文介绍了如何使用标头映射在python中编写元组列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须处理元组的python列表,其中每个元组都包含标头名称,如下所示-我希望所有元组都将映射到该元组中的相应标头.

I have to process python list of tuples where each tuple contains header name as below- I want all the tuple will be mapped to respectives header in that tuple.

    [[(u'Index', u' Broad Market Indices :')],
    [(u'Index', u'CNX NIFTY'), (u'Current', u'7,950.90'), (u'% Change', u'0.03'), (u'Open', u'7,992.05'), (u'High', u'8,008.25'), (u'Low', u'7,930.65'), (u'Prev. Close', u'7,948.90'), (u'Today', u''), (u'52w High', u'9,119.20'), (u'52w Low', u'7,539.50')],
    [(u'Index', u'CNX NIFTY JUNIOR'), (u'Current', u'19,752.40'), (u'% Change', u'0.73'), (u'Open', u'19,765.10'), (u'High', u'19,808.25'), (u'Low', u'19,629.50'), (u'Prev. Close', u'19,609.75'), (u'Today', u''), (u'52w High', u'21,730.80'), (u'52w Low', u'16,271.45')]]

现在想将此列表写入在MS Excel中如下所示的csv中-

Now to want to write this list into csv that looks like in MS Excel as below-

提前谢谢.

推荐答案

我终于找到了解决方法-

I found workaround at last-

将嵌套列表转换成字典并使用dictwriter-

Convert nested lists into dictionary and use dictwriter-

import csv
my_d = []
for i in datalist:
    my_d.append({x:y for x,y in i})

with open("file.csv",'wb') as f:
   # Using dictionary keys as fieldnames for the CSV file header
   writer = csv.DictWriter(f, my_d[1].keys())
   writer.writeheader()
   for d in my_d:
      writer.writerow(d)

但是它改变了列的顺序.如果需要以前的命令,则可以使用标头声明并在dictwrites中使用.

but it changes the order of the columns. If previous order needed i used header declaration and used in the dictwrites.

headers = [u'Index', u'Current', u'% Change', u'Open', u'High', u'Low', u'Prev. Close', u'Today', u'52w High', u'52w Low']

并按如下方式使用

   writer = csv.DictWriter(f, headers)

这解决了我的问题.

这篇关于如何使用标头映射在python中编写元组列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 00:32