如何从列表列表中的每个列表中删除某些索引

时间:2015-12-07 22:42:27

标签: python list function python-3.x indexing

所以要创建我的列表数组,我有这个

def file_processor(filename):
       #create an empty list
    cities_list = []
    try:
        file_read = open(filename, "r")
        for line in file_read:
            split_line = line.split(",")
            cities_list.append(split_line)
        file_read.close()
        return cities_list
    except IOError:
        print("File was not found.")

我需要创建一个新的列表数组,但只有0索引和第7个索引, 但我所做的一切都没有用。

这是我到目前为止的重复列表

def blackWhiteSeglist(filename):
        b_w_list= []
    try:
        file_read = open(filename, "r")
        for line in file_read:
            split_line = line.split(",")
            b_w_list.append(split_line)
        file_read.close()
        for list in b_w_list:
            for line in list:
                b_w_list.pop(1:6,8:12)
        return b_w_list
    except IOError:
        print("File was not found.")

总共有13个索引(0-12),但我只需要0和7

1 个答案:

答案 0 :(得分:2)

只选择你需要的东西:

b_w_list.append([split_line[0], split_line[7]])

整个功能可能如下所示:

def blackWhiteSeglist(filename):
    b_w_list= []
    with open(filename, "r") as file_read:
        for line in file_read:
            split_line = line.split(",")
            b_w_list.append([split_line[0], split_line[7]])
    return b_w_list