通过比较两个列表来删除特定单词

时间:2019-06-18 04:50:56

标签: python list

我有两个列表。

x=['billed_qty','billed_amt','sale_value']

y=['george billed_qty', 'sam billed_amt', 'ricky sale_value', 'donald billed_qty']

我需要消除列表y中出现在列表x中的单词,并希望结果列表为:

z=['george','sam','ricky','donald']

我该如何实现?

谢谢

6 个答案:

答案 0 :(得分:7)

regexlist comprehension一起使用:

comp = re.compile('|'.join(x))
z = [re.sub(comp, '', i).strip() for i in y]

print(z)
['george','sam','ricky','donald']

答案 1 :(得分:3)

在列表理解中将str.joinstr.split一起使用:

z = [' '.join(w for w in s.split() if w not in x) for s in y]
print(z)

输出:

['george', 'sam', 'ricky', 'donald']

答案 2 :(得分:2)

为什么不呢?

print([' '.join(set(i.split()).difference(set(x))) for i in y])

输出:

['george', 'sam', 'ricky', 'donald']

答案 3 :(得分:1)

我不知道它是否涵盖了您的所有情况,但是一个简单的解决方案是:

for i in x:
  for idx, k in enumerate(y):
    y[idx] = k.replace(" "+i, "")

对于array x中的每个值,请将array y中的值替换为空字符串(包括左侧的空格)。

答案 4 :(得分:0)

首先是y的split个元素:

for i in range(0,len(y)):
    y[i] = y[i].split(' ')

所以y为:

[['george', 'billed_qty'], ['sam', 'billed_amt'], ['ricky', 'sale_value'], ['donald', 'billed_qty']]

现在,检查xy的元素是否存在:

for i in range(0,len(y)):
    for j in range(0,len(x)):
        if x[j] in y[i][1]:
            y[i] = y[i][0] 

y更改为:

['george', 'sam', 'ricky', 'donald']

答案 5 :(得分:0)

为此,您可以使用itertools来解决。

解决方法如下。

import itertools

z = [i.split() for i in y]

# This gives us z = [['george', 'billed_qty'], ['sam', 'billed_amt'], ['ricky', 'sale_value'], ['donald', 'billed_qty']]

w = list(itertools.chain.from_iterable(z))

# This gives us w = ['george', 'billed_qty', 'sam', 'billed_amt', 'ricky', 'sale_value', 'donald', 'billed_qty']

output = [a for a in w if a not in x]

# This gives us output = ['george', 'sam', 'ricky', 'donald']

相关问题