【问题标题】:Splitting values out of a CSV Reader Python从 CSV 阅读器 Python 中拆分值
【发布时间】:2013-06-19 07:51:50
【问题描述】:

这是我当前的代码

a_reader = None
a_reader     = open('data.csv', 'rU')
a_csv_reader = csv.reader(a_reader)

for row in a_csv_reader:
       print row
a_reader.close()

count = 0
sum   = 0.0
a_reader     = open('data.csv', 'rU')
a_csv_reader = csv.reader(a_reader)
a_csv_reader.next()

for row in a_csv_reader:
        if count != 0 and row[0] != '':
            sum = sum + float(row[0])
        count = count + 1

a_reader.close()
print 'Number of lines is:',count
print 'Sum is:',sum
return listStation

这会产生下面的结果

['1', '476050', '7709929']    
['2', '473971', '7707713']    
['3', '465676', '7691097']    
['4', '515612', '7702192']    
['5', '516655', '7704405']    
['6', '519788', '7713255']    
['7', '538466', '7683341']    
Number of lines is: 8    
Sum is: 28.0

好的,现在我要做的是拆分 ID、Easting 和 Northing 的值,并将它们附加到一个列表中以创建一个 2d 列表。是否有可能做到这一点?如果可以,能否提供一下代码?

【问题讨论】:

  • 二维列表是指仅包含 ID、Easting 和 Northing 的列表列表吗?
  • @yanhan 是的,它只包含 ID、Easting 和 Northing 的值。即 dl= [[1,476050,7709920],[2,473971,7707713]] 等等这样更清楚吗?
  • 你试过list.append()了吗?
  • @IgnacioVazquez-Abrams 不,我将如何应用 list.append() 方法?请

标签: python list csv split


【解决方案1】:

我想我会用 DictReader 和默认字典来编写你的代码:

import csv

data={}
with open('/tmp/sta.txt','r') as fin:
    reader=csv.DictReader(fin)
    for row in reader:
        for k,v in row.items():
            data.setdefault(k,[]).append(float(v))

print data
print 'Sum is:',sum(data['Station ID'])
print 'Number of lines is:',len(data['Station ID'])+1

打印:

{'Station ID': [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0], 
 'Easting': [476050.0, 473971.0, 465676.0, 515612.0, 516655.0, 519788.0, 538466.0],
 'Northing': [7709929.0, 7707713.0, 7691097.0, 7702192.0, 7704405.0, 7713255.0, 7683341.0]}
Sum is: 28.0
Number of lines is: 8

【讨论】:

    【解决方案2】:

    以下可能有效(但取决于数据 - 将第一列留空/否则列中存在无效数字等...):

    from itertools import islice
    import csv
    
    with open('data.csv') as fin:
        csvin = islice(csv.reader(fin), 1, None) # skip header
        rows = [map(int, row) for row in csvin]
    
    print 'Rows are:'
    print rows
    print 'Number of lines is:', len(stuff)
    print 'Sum is:', sum(row[0] for row in stuff)
    

    【讨论】:

      【解决方案3】:

      我没有您的 data.csv 文件可供测试,但我将通过以下方式重写您的代码并使其生成您想要的 2D 列表:

      import csv
      
      with open('test_data.csv', 'rU') as a_reader:
          a_csv_reader = csv.reader(a_reader)
      
          for row in a_csv_reader:
              print row
      
      with open('test_data.csv', 'rU') as a_reader:
          a_csv_reader = csv.reader(a_reader)
          a_csv_reader.next()
      
          listStation = []
          count = 0
          total = 0.0
          for row in a_csv_reader:
              if count != 0 and row[0] != '':
                  total += float(row[0])
              count += 1
              listStation.append(map(int, row))
      
      print 'Number of lines is:', count
      print 'Sum is:', total
      print 'listStation:', listStation
      

      输出:

      ['ID', 'Easting', 'Northing']
      ['1', '476050', '7709929']
      ['2', '473971', '7707713']
      ['3', '465676', '7691097']
      ['4', '515612', '7702192']
      ['5', '516655', '7704405']
      ['6', '519788', '7713255']
      ['7', '538466', '7683341']
      Number of lines is: 7
      Sum is: 27.0
      listStation: [[1, 476050, 7709929], [2, 473971, 7707713], [3, 465676, 7691097], 
                    [4, 515612, 7702192], [5, 516655, 7704405], [6, 519788, 7713255], 
                    [7, 538466, 7683341]]
      

      注意,我将您命名为 sum 的变量更改为 total 以防止与内置的 sum() 函数发生冲突。

      【讨论】:

        【解决方案4】:

        试试这个:

        import csv
        
        def run():
            count = 0
            sum = 0.0
            listStation = []
            with open('data.csv', 'rU') as a_reader:
                a_csv_reader = csv.reader(a_reader)
                for row in a_csv_reader:
                    if count != 0:
                        if row[0] != '':
                            sum = sum + float(row[0])
                        listStation.append(map(int, row))
                    print 'row =', row
                    count = count + 1
            print 'Number of lines is:',count
            print 'Sum is:', sum
            print listStation
        
        if __name__ == '__main__':
            run()
        

        【讨论】:

          【解决方案5】:
          rows = []
          for row in a_csv_reader:
                 rows.append(row)
          

          将在rows

          [['1', '476050', '7709929']    
          ['2', '473971', '7707713']    
          ['3', '465676', '7691097']    
          ['4', '515612', '7702192']    
          ['5', '516655', '7704405']    
          ['6', '519788', '7713255']    
          ['7', '538466', '7683341']]
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2012-02-28
            • 1970-01-01
            • 1970-01-01
            • 2011-07-08
            • 1970-01-01
            相关资源
            最近更新 更多