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
从python元组列表编写csv_Python_Python 2.7_Python 3.x_Csv - Fatal编程技术网

从python元组列表编写csv

从python元组列表编写csv,python,python-2.7,python-3.x,csv,Python,Python 2.7,Python 3.x,Csv,我有一张这样的清单 lis = [('a', [('happy:units:1', 'cloud:1'), ('sad:units:1', 'rain:2'), 'rating:3']),] 我想要一个像这样的csv 但是我得到了输出 编写一个函数从数据中提取值 def flatten_row(row): """ Transform a row in my weird format into a flat tuple of values. >>>

我有一张这样的清单

lis = [('a', [('happy:units:1', 'cloud:1'), ('sad:units:1', 'rain:2'), 'rating:3']),]
我想要一个像这样的csv

但是我得到了输出

  • 编写一个函数从数据中提取值

    def flatten_row(row):
        """
        Transform a row in my weird format into a flat tuple of values.
    
        >>> ('a', [('happy:units:1', 'cloud:1'), ('sad:units:1', 'rain:2'), 'rating:3'])
        ('a', '1', '1', '1', '2', '3')
        """
        pass  # YOUR CODE HERE
    
  • 利用你的功用获得名利

    for row in lis:
         csv_out.writerow(flatten_row(row))
    

  • 您可以使用下面的代码展平该行,并在该行上进行迭代,以获得所需格式的CSV。假设您的数据始终为给定格式

        lis = [('a', [('happy:units:1', 'cloud:1'), ('sad:units:1', 'rain:2'), 'rating:3']),]
        return_list = list()
        # For the sake of simplicity, Im taking the first element of the given list
        for item in lis[0]:
          # Check if the item is a list
          if type(item) is list:
            for it in item:
              # Iterate over the list item to flatten
              if type(it) is tuple:
                for x in it:
                  return_list.append(x[x.rfind(':')+1:])
              else:
                return_list.append(it[it.rfind(':')+1:])
           else:
             # If it is not a list then simply append the value
             return_list.append(item)
        print(return_list)
    

    您可能应该看看@jagadeesh mn,因为它看起来更具概括性。我的答案非常依赖于不可扩展的定位。然而,我发布了一个快速而肮脏的代码来扁平化

    test=[('bba', [('happy:units:1', 'cloud:1'), ('sad:units:1', 'rain:2'), 'rating:3']),('bcc', [('happy:units:2', 'cloud:2'), ('sad:units:1', 'rain:3'), 'rating:5'])]
    col_id=[];
    col_rating=[];
    col_happy=[];
    col_cloud=[];
    col_sad=[];
    col_rain=[];
    
    for row in test:
        col_id.append(row[0])
        for j,row2 in enumerate(row[1]):
            if(j==2):
                col_rating.append(row2[row2.rfind(':')+1:])
            if(j==0):
                for k,row3 in enumerate(row2):
                    if(k==0):
                        col_happy.append(row3[row3.rfind(':')+1:])
                    if(k==1):
                        col_cloud.append(row3[row3.rfind(':')+1:])
            if(j==1):
                for k,row3 in enumerate(row2):
                    if(k==0):
                        col_sad.append(row3[row3.rfind(':')+1:])
                    if(k==1):
                        col_rain.append(row3[row3.rfind(':')+1:])
    
    
    final_list = list(zip(col_id,col_rating,col_happy,col_cloud,col_sad,col_rain))
    

    不易出错的解决方案:

    li = [('a', [('happy:units:1', 'cloud:1'), ('sad:units:1', 'rain:2'), 'rating:3']),]
    
    li = list(li[0])
    
    li = [li[0]] + li[1]
    
    def flatten_row(inp_lst):
        ou = []
        for x in inp_lst:
            if isinstance(x, basestring):
                ou.append(x)
            else:
                ou += list(x)
        return ou
    
    def get_values(inp_lst):
        ou = []
        for el in inp_lst:
            pos = el.rfind(":") + 1
            ou.append(el[pos:])
        return ou
    
    with open(output_file, "wb") as f:
        writer = csv.writer(f)
        writer.writerows([['id', 'happy:units', 'cloud', 'sad:units', 'rain', 'rating'], 
        get_values(flatten_row(li))])
    

    只要您的输入列表与您提到的模式保持一致,下面的代码就可以工作。我已将项目放入列表中,您可以按照自己的方式将其转换为csv。试试看

    lis = [('a', [('happy:units:1', 'cloud:1'), ('sad:units:1', 'rain:2'), 'rating:3']),]
    res = list()
    for i in xrange(0,len(lis[len(lis)-1])):
            if len(lis[0][i]) > 0:
                    for j in xrange(0,len(lis[0][i])):
                            if len(lis[0][i][j]) >= 1 and type(lis[0][i][j]) == tuple:
                                    for x in xrange(0,len(lis[0][i][j])):
                                            res.append(lis[0][i][j][x])
                            else:
                                    res.append(lis[0][i][j])
    csv = list()
    csv.append(res[0])
    for i in xrange(1,len(res)):
            csv.append(res[i][:-2]+'='+res[i][len(res[i])-1:])
    print("Output: {}".format(csv))
    
    输出:

    ['a', 'happy:units=1', 'cloud=1', 'sad:units=1', 'rain=2', 'rating=3']
    

    这是因为源列表只包含两列。第二列依次包含另一个列表/元组。您需要创建一个新列表,从嵌套元组中提取内容,然后将此新列表写入csv。为什么您的数据采用这种格式?这是某个列表的输出吗?是的,这是一个列表的输出。您是否设法获得了展平代码,还是仍然需要答案?我无法展平代码
    ['a', 'happy:units=1', 'cloud=1', 'sad:units=1', 'rain=2', 'rating=3']