从列表快速选择某些索引项

时间:2019-03-14 20:41:18

标签: python python-2.7

我使用的是Python版本:2.7.12 | Anaconda 4.1.1(64位)| (默认值,2016年6月29日,11:07:13)[MSC v.1500 64位(AMD64)]

我有一个表作为列表列表,说“表”,唯一元素的第一个列表是标题,还有一个列表,说“ cols”和一些表列。我想看看是否有比下面更快的方法来选择与cols项相对应的每个表列表中的项:

def select_cols(table, cols):
    inds = [table[0].index(col) for col in cols]
    return [[row[i] for i in inds] for row in table]

示例:

table = [['a','b','c','d'],[1,2,3,4],[5,6,7,8]]
cols = ['b','d']
print select_cols(table, cols)
>>[['b', 'd'], [2, 4], [6, 8]]

实际上,我已经创建了一个应用程序,该应用程序通过读取大型csv文件来制作这些表,并且以这种方式进行了很多切片,因此我希望此功能尽可能快地运行。另外,我也不想使用熊猫来做这项工作,因为我想保持应用程序轻巧。

2 个答案:

答案 0 :(得分:1)

您可以使用zip函数对行中的列进行分组,通过仅保留cols中的列来过滤列,然后再次zip列组来获得行中的结果。如果要将行作为列表而不是元组,请map行到list

map(list, zip(*(columns for columns in zip(*table) if columns[0] in cols)))

这将返回:

[['b', 'd'], [2, 4], [6, 8]]

答案 1 :(得分:1)

您可以使用运算符def update respond_to do |format| if @contact.update(contact_params) format.html do redirect_to root_path, notice: 'Contact has been updated' end else format.html do render :edit, notice: 'Error' end end end end private def contact_params params.require(:contact).permit( ... :areas_of_interest, ... ) end 从子列表中获取元素:

{"first"=>"1", "second"=>"0", "third"=>"0", "fourth"=>"0", "fifth"=>"1"}

或者,您可以使用函数itemgetter()

from operator import itemgetter

def select_cols(table, cols):
    cols_ = set(cols)
    inds = []

    # get indices of selected elements
    for num, i in enumerate(table[0]):
        if i in cols_:
            inds.append(num)

    # get sublists with selected elements
    iget = itemgetter(*inds)
    return [iget(i) for i in table]
相关问题