Op.Ivy
Op.Ivy

Reputation: 81

Append specific rows from one list to another

Having some difficulty trying to take a 2d list with 7 columns and 10 rows, and append all rows from only columns 4,5 and 6 (or 3,4,5 from index 0) to a new list. The original list is actually a csv and is much, much longer but I've just put part of it in the function for troubleshooting purposes. What I have so far is...

def coords():
    # just an example of first couple lines...
    bigList = [['File','FZone','Type','ID','Lat','Lon','Ref','RVec']
    ['20120505','Cons','mit','3_10','-21.77','119.11','mon_grs','14.3'] 

    newList=[] 
    for row in bigList[1:]: # skip the header   
        newList.append(row[3])
    return newList       # return newList to main so it can be sent to other functions

This code gives me a new list with 'ID' only but I also want 'Lat' and 'Lon'. The new list should look like...['3_10', '-21.77','119.11']['4_10','-21.10'...] I tried re-writing newList.append(row[3,4,5])...and of course that doesn't work but not sure how to go about it.

Upvotes: 1

Views: 1702

Answers (1)

Blender
Blender

Reputation: 298392

row[3] refers to the fourth element. You seem to want the fourth through sixth elements, so slice it:

row[3:6]

You could also do this all with a list comprehension:

newList = [row[3:6] for row in myList[1:]]

Upvotes: 2

Related Questions