Check if an item is in a nested list

后端 未结 8 1636
死守一世寂寞
死守一世寂寞 2020-11-28 12:32

in a simple list following check is trivial:

x = [1, 2, 3]

2 in x  -> True

but if it is a list of list, such as:

x = [[         


        
8条回答
  •  离开以前
    2020-11-28 13:33

    My code is based on Óscar López's solution. His solution wasn't exactly what I needed for my problem but it gave enough info for me to figure out my problem. So if you have nested elements in one list and need to see if they're in another nested list, this would work.

    #!python2
    
    lst1 = [['a', '1'], ['b', '2'], ['c', '3'], ['d', '4'], ['e', '5']]
    lst2 = [['b', '2'], ['d', '4'], ['f', '6'], ['h', '8'], ['j', '10'], ['l', '12'], ['n', '14']]
    
    # comparing by index 0, prints lst1 items that aren't in lst2
    for i in lst1:
        if not any(i[0] in sublst for sublst in lst2):
            print i
    '''
    ['a', '1']
    ['c', '3']
    ['e', '5']
    '''
    
    print
    
    # comparing by index 0, prints lst2 items that aren't in lst1
    for i in lst2:
        if not any(i[0] in sublst for sublst in lst1):
            print i
    '''
    ['f', '6']
    ['h', '8']
    ['j', '10']
    ['l', '12']
    ['n', '14']
    '''
    

提交回复
热议问题