如何从字符串列表中删除单词列表?

时间:2015-09-01 06:44:46

标签: python

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

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

所以输出将是

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

4 个答案:

答案 0 :(得分:4)

您可以使用设置操作:

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

可能的结果:

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

如果您想保留订单,可以执行以下操作:

s = set(list1)

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

结果:

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

答案 1 :(得分:1)

您可以使用set。使用set时,您也不会复制任何项目。

这是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**']

答案 2 :(得分:1)

如果你想

  1. *
  2. 中删除List2
  3. 不在list1
  4. 中的元素

    尝试:

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

答案 3 :(得分:0)

你可以这样做。迭代list2中list1单词的列表,然后使用迭代器删除单词。这对重复的单词不起作用。

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