按值和索引列表过滤列表

时间:2016-03-22 06:03:25

标签: python list python-3.x

def find_value_indexes(item_list, index_list, v):
    """ (list of object, list of int, object) -> list of int

    Precondition: the values in index_list are valid indexes in item_list.

    v may appear multiple times in item_list.  index_list contains zero or
    more indexes.  
    Return a list of the indexes from index_list at which v
    appears in item_list.

    >>> find_value_indexes([6, 8, 8, 5, 8], [0, 2, 4], 8)
    [2, 4]
    """

    result = []
    for i in range(len(item_list)):
        for j in range(len(index_list)):
            if item_list[i] == v:
                result.append(index_list[j])
    return result

我的功能不起作用,因为它返回的比我应该得到的多。我该怎么办?

1 个答案:

答案 0 :(得分:0)

您无需迭代item_list - 只需迭代index_list并将其元素用作item_list的索引:

result = []
for i in index_list:
    if item_list[i] == v:
         result.append(i)
return result

或者,更优雅的是,使用列表推导作为单行:

return [i for i in index_list if item_list[i] == v]