Kees Kees - 1 year ago 60
Python Question

List of lists (not just list) in Python

I want to make a list of lists in python.

My code is below.

import csv
f = open('agGDPpct.csv','r')
inputfile = csv.DictReader(f)

list = []

next(f) ##Skip first line (column headers)

for line in f:
array = line.rstrip().split(",")
print list

I'm pulling only select columns from every row. My code pops this all into one list, as such:

['ABW', 'Aruba', '0.506252445', '0.498384331', '0.512418427', '', '', 'AND', 'Andorra', '', '', '', '', '', 'AFG', 'Afghanistan', '30.20560247', '27.09154001', '24.50744042', '24.60324707', '23.96716227'...]

But what I want is a list in which each row is its own list:
Any tips?

Answer Source

You are almost there. Make all your desired inputs into a list before appending. Try this:

import csv 
with open('agGDPpct.csv','r') as f:
  inputfile = csv.DictReader(f)
  list = []

  for line in inputfile: 
    list.append([line[1], line[0], line[53], line[54], line[55], line[56], line[57]])
print list
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download