Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Python2.7中从元组列表创建csv文件?_Python_Python 2.7_Csv - Fatal编程技术网

如何在Python2.7中从元组列表创建csv文件?

如何在Python2.7中从元组列表创建csv文件?,python,python-2.7,csv,Python,Python 2.7,Csv,我有一个元组列表,我试图找出如何创建一个csv文件,其中键作为列标题,值作为列值 下面是元组的示例列表: [('d_conversion_rate', 1), ('prev_2wk_visit_count', 0.0), ('sku_id', '100088-01'), ('prev_1wk_uniq_purch_cnt', 0.0)] [('d_conversion_rate', 0), ('prev_2wk_visit_count', 6.0), ('sku_id', '100088-02'

我有一个元组列表,我试图找出如何创建一个csv文件,其中键作为列标题,值作为列值

下面是元组的示例列表:

[('d_conversion_rate', 1), ('prev_2wk_visit_count', 0.0), ('sku_id', '100088-01'), ('prev_1wk_uniq_purch_cnt', 0.0)]
[('d_conversion_rate', 0), ('prev_2wk_visit_count', 6.0), ('sku_id', '100088-02'), ('prev_1wk_uniq_purch_cnt', 0.0)] 
[('d_conversion_rate', 5), ('prev_2wk_visit_count', 7.0), ('sku_id', '100088-03'), ('prev_1wk_uniq_purch_cnt', 0.0)]
预期的csv文件应具有:

converstion_rate,  sku_id, prev_1wk_uniq_purch_cnt
1,                  100088-02, 0.0
0,                  100088-03, 6.0
5,                  100088-04, 7.0
这是我写的代码:

import os
import sys
import csv
import string
import random


def import_data_to_csv(dict_d):
    with open('C:/Reports/SI_Reconciliation_Reporting/2015/output/2015-04-19/test_dump.csv', 'w') as outfile:
        fp = csv.DictWriter(outfile, dict_d[0].keys())
        fp.writeheader()
        fp.writerows(dict_d)



for row in sku_weekL:
                #print row.items()
                for key, value in row.items():
                    sku_weekTemp.append((key, value))
                print sku_weekTemp

            #print sku_weekL
            #print sku_weekL
            #print dir(sku_weekL)
            import_data_to_csv(sku_weekTemp)
但是运行脚本时,我得到一个错误,即tuple对象没有属性键


有没有办法解决这个问题?

错误试图告诉您dict_d[0]是一个元组对象,因此没有方法键,只有dict有方法键

首先,您应该有一个按首选顺序排列的列名列表:

column_names = ['d_conversion_rate', 'sku_id', 'prev_1wk_uniq_purch_cnt']
因为行已经是带有这些键的dict,所以不需要对它们进行变换

当您拥有所有值行时,您可以将其与列名称一起使用来写入:

def import_data_to_csv(value_rows, column_names):
    with open('C:/Reports/SI_Reconciliation_Reporting/2015/output/2015-04-19/test_dump.csv', 'w') as outfile:
        fp = csv.DictWriter(outfile, column_names)
        fp.writeheader()
        fp.writerows(value_rows)
编辑:我错过了你使用DictWriter的机会,所以没有必要将dicts转换成列表

edit2:一个例子:

考虑到瓦卢这样的行

val_rows = [
    {'sku_id': 1, 'd_conversion_rate': 2, 'prev_1wk_uniq_purch_cnt': 3},
    {'sku_id': 4, 'd_conversion_rate': 5, 'prev_1wk_uniq_purch_cnt': 6}
]
您可以像这样使用上面的函数

col_names = ['d_conversion_rate', 'sku_id', 'prev_1wk_uniq_purch_cnt']
import_data_to_csv(val_rows, col_names)

# or dynamically

import_data_to_csv(val_rows, val_rows[0].keys())
list_of_list_of_tuples = [
    [('d_conversion_rate', 1), ('prev_2wk_visit_count', 0.0), ('sku_id', '100088-01'), ('prev_1wk_uniq_purch_cnt', 0.0)],
    [('d_conversion_rate', 0), ('prev_2wk_visit_count', 6.0), ('sku_id', '100088-02'), ('prev_1wk_uniq_purch_cnt', 0.0)],
    [('d_conversion_rate', 5), ('prev_2wk_visit_count', 7.0), ('sku_id', '100088-03'), ('prev_1wk_uniq_purch_cnt', 0.0)]
]

val_rows = [{tup[0]: tup[1] for tup in row} for row in list_of_list_of_tuples]
如果您的数据未格式化为DICT列表,则必须进行转换。从上面的问题中获取元组列表,我们可以将其转换为这样的dict列表

col_names = ['d_conversion_rate', 'sku_id', 'prev_1wk_uniq_purch_cnt']
import_data_to_csv(val_rows, col_names)

# or dynamically

import_data_to_csv(val_rows, val_rows[0].keys())
list_of_list_of_tuples = [
    [('d_conversion_rate', 1), ('prev_2wk_visit_count', 0.0), ('sku_id', '100088-01'), ('prev_1wk_uniq_purch_cnt', 0.0)],
    [('d_conversion_rate', 0), ('prev_2wk_visit_count', 6.0), ('sku_id', '100088-02'), ('prev_1wk_uniq_purch_cnt', 0.0)],
    [('d_conversion_rate', 5), ('prev_2wk_visit_count', 7.0), ('sku_id', '100088-03'), ('prev_1wk_uniq_purch_cnt', 0.0)]
]

val_rows = [{tup[0]: tup[1] for tup in row} for row in list_of_list_of_tuples]
希望这一点现在能说清楚

编辑3: 你在评论中写的东西缺少一些信息,所以我不得不猜测

for i in List:
    sku_L = list()  # I'm assuming you're appending each sku_L to another list somewhere further down
    for row in insL:  # I'm assuming insL is calculated in the outer loop or is just i
        insertD = dict()
        # here I assign all the values to the keys of the dictionary
        sku_L.append(insertD)
        pprint(sku_L)
您不希望每个字典都有一个新的列表,所以我会从循环中取出列表实例化。pprint的目的是在不使用循环的情况下使用它,这样您就可以看到整个过程

sku_L = list()  # only one list now
for i in List:
    for row in i:  # insL is probably just i
        insertD = dict()
        # here I assign all the values to the keys of the dictionary
        sku_L.append(insertD)

pprint(sku_L)  # printing the whole thing should be a list of dicts
我很确定你的数据实际上只是一个记录列表,每个记录都有固定位置的数据。如果是这种情况,您可以将其简化很多:

input_list = [  # this is a list of records
    [1, 0.0, 0.0, '100088-01'],
    [1, 0.0, 6.0, '100088-02']
]

sku_L = list()
for row in input_list:
    insertD = {
        'd_conversion_rate': row[0],
        'prev_2wk_visit_count': row[1],
        'prev_1wk_uniq_purch_cnt': row[2],
        'sku_id': row[3]
    }
    sku_L.append(insertD)

pprint(sku_L)

这是一个基于我对你问题的理解的解决方案。 如果有什么问题可以随便问。我个人不喜欢python标准库csv,并且在需要编写csv文件时总是不使用它

def asDic(listOfTuple):
    """ Convert a list of tuple [(key,value)] into a dictionary """
    return {i:j for (i,j) in listOfTuple}

def exportLine(lineMembers, outputFile, separator):
    """
    exportLine(["lineMembers"foo", "bar", "foo"], file, "separator",")
        -> file.write("foo, bar, foo\n")
    """
    lineString = ""
    for i in range(len(lineMembers)-1):
        lineString += str(lineMembers[i]) + separator
    #Append the last element without a separator, instead add a end of line
    lineString += str(lineMembers[-1]) + "\n"
    outputFile.write(lineString)

def exportCSV(data, headers, outputFile, separator = ", "):
    """
    Exports the data into the outputFile using the given headers.
    It is possible to generate any separated value file by overriding the default separator.

    data : a list of dict object. Their content will be accesed using the values of headers as keys.
    """
    #export the headers
    exportLine(headers, outputFile, separator)

    for dataset in data : 
        #Build the data line
        exportData = [ dataset[header] for header in headers ]
        #and export it
        exportLine(exportData, outputFile, separator)


if __name__ == "__main__":

    row1 = [('d_conversion_rate', 1), ('prev_2wk_visit_count', 0.0), ('sku_id', '100088-01'), ('prev_1wk_uniq_purch_cnt', 0.0)]
    row2 = [('d_conversion_rate', 0), ('prev_2wk_visit_count', 6.0), ('sku_id', '100088-02'), ('prev_1wk_uniq_purch_cnt', 0.0)]
    row3 = [('d_conversion_rate', 5), ('prev_2wk_visit_count', 7.0), ('sku_id', '100088-03'), ('prev_1wk_uniq_purch_cnt', 0.0)]

    data = [row1, row2, row3]

    #get the list of headers that will be exported
    columnHeader = [i for (i,j) in data[0]]
    #transform the data to allow access them by field
    data = [asDic(row) for row in data]

    #you may add here whatever code you want in order to sort/filter/remove some headers here.
    #Removing one header will remove the column from the final export.
    columnHeader.pop(1)#commenting this will add the column prev_2wk_visit_count to the file.

    outputFile = open("./output.csv", 'w')
    exportCSV(data, columnHeader, outputFile)
    outputFile.close()

欢迎来到堆栈溢出!这里通常期望您展示您编写的代码或描述您为解决问题所做的研究。正如您的问题目前编写的那样,它听起来像是对代码的请求。您是否有任何尝试可以与我们分享?请不要使用代码段,因为它们是专为您而设计的。任务一:将列表平铺为仅包含值;任务二使用CSV编写器:@skrrgwasme我在上面包含了一些代码。元组的数据结构列表是必需的,或者您可以更改此输入吗?我完全按照您所说的做了,通过传递insertD.values和insertD.keys调用import_data_to_CSV函数,但我得到了TypeError:“int”对象不是iterableI添加了一个示例,希望这能有所帮助:老实说,我确实理解你给我的方向,但当我打印所有值的列表循环时,我的字典列表显示为[{'sku_id':1,'d_conversion_rate':2,'prev_1wk_uniq_purch_cnt':3}],{'sku id':4,'d_conversion_rate':5,'prev_1wk_uniq_purch_cnt':6}],每一个在打印时都会出现一行。那么我怎样才能使它像[{'sku_id':1,'d_conversion_rate':2,'prev_1wk_uniq_purch_cnt':3},{'sku id':4,'d_conversion_rate':5,'prev_1wk_uniq_purch_cnt':6}],这样我就可以完全按照你的建议去做。因为当我喜欢你用这个代码来指导我的时候:导入数据到csvval_行,val_行[0].keys我在下面得到一个定义的错误:fp.writerowsvalues\u rows name错误:未定义全局名称“values\u rows”。它不理解values\u行,因为它没有定义任何where,但是values\u行是字典列表。所以每个dict都被包装在一个列表中,其中包含一个元素dict本身?只需使用val_rows=maplambda x:x[0]调用它,您的_列表就会从列表中为您的_列表的每个元素提取dict