【问题标题】:Writing a csv from a python list of tuples从元组的python列表中编写一个csv
【发布时间】:2017-07-20 07:09:45
【问题描述】:

我有一个这样的列表

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

我想要一个这样的 csv

 import csv

 with open('Yo456!.csv', 'wb') as out:
     csv_out = csv.writer(out, delimiter=',')
     csv_out.writerow(['id', 'happy:units', 'cloud', 'sad:units', 'rain', 'rating'])
     for row in lis:
         csv_out.writerow(row)

但我得到了输出

【问题讨论】:

  • 这是因为您的源列表仅包含两列。第二列又包含另一个列表/元组。您需要创建一个从嵌套元组中提取内容的新列表,然后将此新列表写入 csv。
  • 为什么你的数据是这种格式的?这是什么东西的输出吗?
  • 是的,它是一个列表的输出
  • 您是否设法获得了扁平化代码或者您仍然需要答案?
  • 我无法展平代码

标签: python python-2.7 python-3.x csv


【解决方案1】:

您可以使用以下代码展平该行并在该行上对其进行迭代以获得所需格式的 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)

【讨论】:

    【解决方案2】:
    1. 编写一个函数从数据中提取值。

      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
      
    2. 利用你的功能获得名誉和利润

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

    【讨论】:

      【解决方案3】:

      您可能应该看看@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))
      

      【讨论】:

        【解决方案4】:

        一个不易出错的解决方案:

        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))])
        

        【讨论】:

          【解决方案5】:

          只要您的输入列表与您提到的模式一致,下面的代码就可以工作。我已将项目放入列表中,您可以按照自己的方式将它们转换为 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']
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2013-12-20
            • 1970-01-01
            • 1970-01-01
            • 2023-03-15
            • 1970-01-01
            • 2018-05-13
            相关资源
            最近更新 更多