0

我很抱歉,因为我对 python 很陌生。我正在遍历几个名称,它们都得到相同的字典键和值。我怎样才能只打印一次密钥并继续按照迭代将值附加到csv?

     for name in namelist:
       print >> out,','.join(data.keys())
       print >> out,','.join(data.values())
     fundamental_out.close()

输出看起来像这样

   >>'key1,key2,key3'
   >>'value1,value2,value3'
   >>'key1,key2,key3'
   >>'value1,value2,value3'

说 key3 是名称,key1 和 2 是数字

我怎样才能得到像

   >>'key1,key2,key3'
   >>'value1,value2,value3'
   >>'value1,value2,value3'

还有一种方法可以按顺序对数据字典进行排序,以便 key3 (即名称将是第一列)?

   >>'key3,key1,key2'
   >>'value3,value1,value2'
   >>'value3,value1,value2'

谢谢!

4

2 回答 2

0

您可以使用自然排序对字典键进行排序:

import re

def natural_sort(l): 
    #https://stackoverflow.com/a/4836734/846892
    convert = lambda text: int(text) if text.isdigit() else text.lower() 
    alphanum_key = lambda key: [ convert(c) for c in re.split('([0-9]+)', key) ] 
    return sorted(l, key = alphanum_key)

sorted_keys = ['key3'] + natural_sort(data.viewkeys() - {'key3'})

print >> out, ','.join(keys)
for name in namelist:
       print >> out, ','.join(str(data[k]) for k in keys)
于 2013-11-11T04:12:13.013 回答
0
from itertools import chain
def arrange(l):
    return list(chain([l[-1]], l[:-1]))

print ','.join(arrange(map(lambda x: str(x), namelist.keys())))
print ','.join(arrange(map(lambda x: str(x), namelist.values())))
于 2013-11-11T04:15:10.623 回答