简体   繁体   中英

How to remove list of words from a list of strings?

list1=['water', 'analog', 'resistance', 'color', 'strap','men', 'stainless', 'timepiece','brown','fast']

list2=['water resistant','water','red strap','digital and analog','analog', 'men', 'stainless steel']

So that output will be

list=['water resistant','red strap','digital and analog','stainless steel']

You could use set operations:

list(set(list2) - set(list1))

Possible result:

['red strap', 'digital and analog', 'stainless steel', 'water resistant']

If you want to preserve the order you could do the following:

s = set(list1)

[x for x in list2 if x not in s]

Result:

['water resistant', 'red strap', 'digital and analog', 'stainless steel']

You can use set for this. Also with set you won't have any item duplicated.

Here is output from Python Shell

>>> set1 = set(list1)
>>> set2 = set(list2)
>>> set1
set(['brown', 'timepiece', 'color', 'stainless', 'men', 'resistance', 'fast', 'strap', 'water', 'analog'])
>>> set1-set2
set(['brown', 'timepiece', 'color', 'stainless', 'resistance', 'fast', 'strap'])
>>> set2-set1
set(['red strap', '**water resistant**', '**stainless steel**', '**digital and analog**'])
>>> for each in (set2-set1):
        print each

red strap
**water resistant**
**stainless steel**
**digital and analog**
>>> list3 = list(set2-set1)
>>> list3
['red strap', '**water resistant**', '**stainless steel**', '**digital and analog**']

If you want to

  1. remove * from List2 items
  2. elements not in list1

Try:

>>> list = [x.replace('*', '') for x in list2 if x not in list1]
>>> list
['water resistant', 'red strap', 'digital and analog', 'stainless steel']
>>> 

You could do it this way. Iterate through a list of list1 words which are in list2, then use the iterator to remove words. This does not work for repeated words.

>>> for s in [a for a in list1[:] if a in list2[:]]:
...    list2.remove(s)
... 
>>> list2
['water resistant', 'red strap', 'digital and analog', 'stainless steel']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM