Python 将包含字符串和字典的列表写入csv文件

Python 将包含字符串和字典的列表写入csv文件,python,list,csv,dictionary,Python,List,Csv,Dictionary,我有一个列表,在列表的第一个元素中有一个字符串,在第二个元素中有一个字典,它有一些标志和与之相关的计数,我如何将它写入python中的csv文件 名单如下 ['(RenderThread)', Counter({'flags=4': 752, 'flags=40': 299, 'flags=10004': 283, 'flags=80': 203, 'flags=90002': 36, 'flags=10080': 31, 'flags=100

我有一个列表,在列表的第一个元素中有一个字符串,在第二个元素中有一个字典,它有一些标志和与之相关的计数,我如何将它写入python中的csv文件

名单如下

['(RenderThread)', 
  Counter({'flags=4': 752, 'flags=40': 299, 'flags=10004': 283,
           'flags=80': 203, 'flags=90002': 36, 'flags=10080': 31, 
           'flags=100': 23, 'flags=10040': 14, 'flags=10100': 9})]
<type 'list'>
这是我的代码片段

with open(outputcsv,'wb') as outcsv:
    writer = csv.writer(outcsv,delimiter=',')
    for x in threads:
        writer.writerows([x.split(',')])
        w = csv.DictWriter(outcsv,data1)
        w.writerow(counter1)
        writer.writerows('\n')

其中data1=[thr1,counter1]

我正在猜测您的数据是什么样子的,但我认为您可以将列表中的两个项目组合成一个dict,然后使用
DictWriter
来编写整个内容。有几个奇怪的地方,包括我对数据列表外观的猜测,以及即使在输出中显示了大量空格填充,您仍然需要逗号分隔符。工作示例确实可以帮助解决其中的一些问题

import csv

# example input
data = ['(RenderThread)', {'flags=4': 752, 'flags=40': 299}]

# presumably its one of many in an outer list
threads = [data]

def render_thread_iter(threads):
    """Given an interator that emits [RenderThread, FlagsDict] lists,
    iterate dicts where render thread is added to flags dict.
    """
    for data in threads:
        d = {'RenderThread':data[0]}
        d.update(data[1])
        yield d

with open('output.csv','w', newline='') as outcsv:
    # create list of header fields
    fieldnames = ['RenderThread'] + sorted(threads[0][1].keys())
    writer = csv.DictWriter(outcsv, delimiter=',', fieldnames=fieldnames)
    # write rendered dicts
    writer.writeheader()
    writer.writerows(render_thread_iter(threads))

第二个元素是一个叫做计数器的东西。。。那是什么?你说线程中x的
。。。但您只显示一个列表。您显示的列表是否只是外部列表中的一个项目?计数器正在计算事件中标志出现的次数。因为现在我使用的是单个列表,我将把它扩展到所有线程,一旦我解决了如何实现这一点,显示的输出基本上是csv文件中数据外观的快照,因此为了使其类似,我添加了许多空格
import csv

# example input
data = ['(RenderThread)', {'flags=4': 752, 'flags=40': 299}]

# presumably its one of many in an outer list
threads = [data]

def render_thread_iter(threads):
    """Given an interator that emits [RenderThread, FlagsDict] lists,
    iterate dicts where render thread is added to flags dict.
    """
    for data in threads:
        d = {'RenderThread':data[0]}
        d.update(data[1])
        yield d

with open('output.csv','w', newline='') as outcsv:
    # create list of header fields
    fieldnames = ['RenderThread'] + sorted(threads[0][1].keys())
    writer = csv.DictWriter(outcsv, delimiter=',', fieldnames=fieldnames)
    # write rendered dicts
    writer.writeheader()
    writer.writerows(render_thread_iter(threads))