How to remove index list from another list in python?

This question already has an answer here:

  • Finding the index of an item given a list containing it in Python 23 answers

  • 尝试这个:

    >>> list_1=['a', 'b', 'c', 'd']
    >>> list_2 = ['1', 'e', '1', 'e']
    >>> index_list = ['1', '3']
    >>> index_list = [int(i) for i in index_list] # convert str to int for index
    >>> list_1 = [i for n, i in enumerate(list_1) if n not in index_list]
    >>> list_2 = [i for n, i in enumerate(list_2) if n not in index_list]
    >>> list_1
    ['a', 'c']
    >>> list_2
    ['1', '1']
    >>> 
    

    How about:

    list_1, list_2 = zip(*((x, y) for x, y in zip(list_1, list_2) if f(x)))
    

    Where f is a function that tests whether a certain value in list_1 matches your condition.

    For example:

    list_1 = ['a', 'b', 'c', 'd']
    list_2 = ['1', 'e', '1', 'e']
    
    
    def f(s):
        return s == 'b' or s == 'c'
    
    list_1, list_2 = zip(*((x, y) for x, y in zip(list_1, list_2) if f(x)))
    
    print list_1
    print list_2
    

    ('b', 'c')

    ('e', '1')

    (Note that this method actually makes list1 and list2 into tuples, which may or may not be okay for your use case. If you really need them to be lists, then you can very easily convert them to lists with the line:

    list_1, list_2 = list(list_1), list(list_2)
    

    right after the "primary" line.)


    A little late to the party, But here is another version.

    list_1=['a', 'b', 'c', 'd']
    
    list_2=['1', 'e', '1', 'e']
    index_list = ['1', '3']
    
    
    #convert index_list to int
    index_list = [ int(x) for x in index_list ]
    
    #Delete elements as per index_list from list_1
    new_list_1 = [i for i in list_1 if list_1.index(i) not in index_list]
    
    #Delete elements as per index_list from list_2
    new_list_2 = [i for i in list_2 if list_2.index(i) not in index_list]
    
    print "new_list_1=", new_list_1
    print "new_list_2=", new_list_2
    

    Output

    Python 2.7.9 (default, Dec 10 2014, 12:24:55) [MSC v.1500 32 bit (Intel)] on win32
    Type "copyright", "credits" or "license()" for more information.
    >>> ================================ RESTART ================================
    >>> 
    new_list_1= ['a', 'c']
    new_list_2= ['1', '1']
    >>> 
    
    链接地址: http://www.djcxy.com/p/28116.html

    上一篇: 了解项目在阵列中的位置

    下一篇: 如何从Python中的另一个列表中删除索引列表?