Python check if Items are in list

前端 未结 4 877
慢半拍i
慢半拍i 2021-01-20 14:01

I am trying to iterate through two lists and check if items in list_1 are in list_2. If the item in list_1 is in list_2 I would like to print the item in list_2. If the ite

相关标签:
4条回答
  • 2021-01-20 14:05
    for i in list_1:
        found = False
        for x in list_2:
            if i in x:
                found = True
                print(x)
        if found == False:
            print(i)
    
    0 讨论(0)
  • 2021-01-20 14:09
    for i in range(len(list_1)):
      if list_1[i] in list_2[i]:
        print(list_2[i])
      else:
        print(list_1[i])
    
    0 讨论(0)
  • 2021-01-20 14:20

    Oneliner:

    [print(i) for i in ["Letter {}".format(i) if "Letter {}".format(i) in list_2 else i for i in list_1]]
    

    Outputs:

    Letter A
    B
    Letter C
    Letter D
    Y
    Letter Z
    
    0 讨论(0)
  • 2021-01-20 14:24

    You can write:

    for i in list_1:
        found = False
        for x in list_2:
            if i in x:
                found = True
                break
        if found:
            print(x)
        else:
            print(i)
    

    The approach above ensure that you either print x or i and we only print one value per element in list_1.

    You could also write (which is the same thing as above but makes use of the ability to add an else to a for loop):

    for i in list_1:
        for x in list_2:
            if i in x:
                print(x)
                break
        else:
            print(i)
    
    0 讨论(0)
提交回复
热议问题