1

尝试获取具有 7 列和 10 行的 2d 列表并将仅来自第 4,5 和 6 列(或来自索引 0 的 3,4,5)的所有行附加到新列表时遇到一些困难。原始列表实际上是一个 csv,而且要长得多,但我只是将其中的一部分放入函数中以进行故障排除。到目前为止我所拥有的是...

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

这段代码给了我一个只有“ID”的新列表,但我也想要“Lat”和“Lon”。新列表应如下所示...['3_10', '-21.77','119.11']['4_10','-21.10'...] 我尝试重写 newList.append(row[3,4 ,5])...当然这不起作用,但不知道该怎么做。

4

1 回答 1

2

row[3]指第四个元素。你似乎想要第四个到第六个元素,所以切片它:

row[3:6]

你也可以通过列表理解来完成这一切:

newList = [row[3:6] for row in myList[1:]]
于 2013-05-18T00:00:55.837 回答