Create a coordinate pair from this code

百般思念 提交于 2019-12-13 04:24:02

问题


Here is my current code

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

This produces the results below

['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

Ok so the output that I want is shown below in a double list.

[[476050, 7709929],[473971, 7707713],[465676, 7691097],[515612, 7702192],[516655, 7704405],[519788, 7713255],[538466, 7683341]]

How can I alter my code to produce the result as a double list as shown above. Is it possible to create a doublelist of coordinate pairs as shown above. Can you help me?

Any help is appreciated.


回答1:


Slice off the last two elements, then append.

>>> ['1', '476050', '7709929'][1:3]
['476050', '7709929']



回答2:


import csv
import itertools

with open('data.csv') as f:
    reader = csv.reader(f)
    rows = []
    total = 0
    for row in itertools.islice(reader, 1, None): # Skip a header
        if row[0]:
            total += int(row[0])
            rows.append(row[1:])

print 'Number of lines is:', len(rows)
print 'total is', total
print rows



回答3:


Instead of:

for row in a_csv_reader:
    print row

Use a list comprehension to slice the list:

for i in [row[-2:] for row in a_csv_reader]:
    print i

Which prints:

['476050', '7709929']
['473971', '7707713']
['465676', '7691097']
['515612', '7702192']
['516655', '7704405']
['519788', '7713255']
['538466', '7683341']

So thus [row[-2:] for row in a_csv_reader] is:

[['476050', '7709929'], ['473971', '7707713'], ['465676', '7691097'], ['515612', '7702192'], ['516655', '7704405'], ['519788', '7713255'], ['538466', '7683341']]

Which is your expected output.



来源:https://stackoverflow.com/questions/17248550/create-a-coordinate-pair-from-this-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!