please wait

  • Ekta Singhania Mar-13-2019 06:48:42 AM ( 2 months ago )

    I have two lists looking like:

    list1 = ['bj-100-cy','bj-101-hd','sh-200-pd','sh-201-hp']
    list2 = [100, 200]


    I want to substring filter list1 by elements of list2 and get expected output as follows:


    outcome = ['bj-100-cy', 'sh-200-pd']


    When doing:


    list1 = str(list1)
    list2 = str(list2)
    outcome = [x for x in list2 if [y for y in list1 if x in y]]

    I get a result like this: ['[', '1', '0', '0', ',', ' ', '2', '0', '0', ']']. How can I filter it correctly?

  • Apoorva Saxena Mar-13-2019 06:50:19 AM ( 2 months ago )

    List comprehension and any:


    [i for i in list1 if any(i for j in list2 if str(j) in i)]

    any to check if any element of list2 is a substring of the list1 item (__contains__) being iterated over


    In [92]: list1 = ['bj-100-cy','bj-101-hd','sh-200-pd','sh-201-hp']
        ...: list2 = [100, 200]
    In [93]: [i for i in list1 if any(i for j in list2 if str(j) in i)]
    Out[93]: ['bj-100-cy', 'sh-200-pd']
  • Pooja Bhardwaj Mar-13-2019 06:51:57 AM ( 2 months ago )

    You can use any:

    list1 = ['bj-100-cy','bj-101-hd','sh-200-pd','sh-201-hp']
    list2 = [100, 200]
    list2 = [str(x) for x in list2]
    outcome = [s for s in list1 if any(x in s for x in list2)]

    any returns True if any of the conditions you give it are True.

  • Imran Malik Mar-13-2019 06:53:17 AM ( 2 months ago )
    list1 = str(list1)
    list2 = str(list2)

    You are converting your list into a string with the above statements. So when you iterate in a for loop, you are iterating each characters, instead of each word.

    So you should remove string conversion and instead do a list comprehension as follows. Also, in your outcome file instead of checking if the word in list2 is in list1, you are checking the opposite. So you got like 100 and 200 as chars which are in list 2.

    list1 = ['bj-100-cy','bj-101-hd','sh-200-pd','sh-201-hp']
    list2 = [100, 200]
    outcome = [x for x in list1 for y in list2 if str(y) in x]
  • Arminder Gill Mar-13-2019 06:54:31 AM ( 2 months ago )

    Another alternative list comprehension :

    >>> list1 = ['bj-100-cy','bj-101-hd','sh-200-pd','sh-201-hp']
    >>> list2 = [100, 200]
    >>> occur = [i for i in list1  for j in list2 if str(j) in i]
    >>> occur
    ['bj-100-cy', 'sh-200-pd']

Please login

Similar Discussion

Recommended For You