Kees Kees - 2 months ago 7
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(",")
list.append(array[1])
list.append(array[0])
list.append(array[53])
list.append(array[54])
list.append(array[55])
list.append(array[56])
list.append(array[57])
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:
[[a,b,c][d,e,f][g,h,i]...]
Any tips?

Answer

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
Comments