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

这个问题在这里已经有了答案:

  • 在Python中找到一个包含它的列表的索引23个答案

  • 尝试这个:

    >>> 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']
    >>> 
    

    怎么样:

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

    其中f是测试list_1中的某个值是否与您的条件匹配的函数。

    例如:

    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')

    (注意,这个方法实际上使得list1list2成为元组,这对你的用例可能会也可能不会,如果你真的需要它们作为列表,那么你可以很容易地将它们转换为列表:

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

    紧跟在“主”线之后。)


    晚会有点晚,但这里是另一个版本。

    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
    

    产量

    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/28115.html

    上一篇: How to remove index list from another list in python?

    下一篇: Get JSON list index by value in Python