簡體   English   中英

從列表列表中快速選擇某些索引的項目

[英]Select items of certain indices from a list of lists fast

我使用的是 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 文件來制作這些表格,並以這種方式進行了大量切片,因此我希望此功能盡可能快地運行。 此外,我不想在這項工作中使用 Pandas,因為我想讓應用程序保持輕便。

您可以使用zip函數對行中的列進行分組,通過僅保留cols列來過濾列,然后再次zip列組以獲得行中的結果。 如果要將行作為列表而不是元組,請將行maplist

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

這將返回:

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

您可以使用操作符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]

或者,您可以使用函數compress()

from itertools import compress

def select_cols(table, cols):
    cols_ = set(cols)

    # build selector list
    sel = [i in cols_ for i in table[0]]

    # get sublists with selected elements
    return [list(compress(i, sel)) for i in table]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM