Create a Coordinate Pair from This Code

Create a Coordinate Pair from This Code

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.

3 Answers

Slice off the last two elements, then append.

>>> ['1', '476050', '7709929'][1:3]
['476050', '7709929']
5
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

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.

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Sarah Jenkins
Author

Sarah Jenkins

Sarah Jenkins is a veteran tech journalist with over 12 years of experience covering artificial intelligence, mobile innovations, and digital ethics. Her insights have appeared in leading technology publications worldwide.