如何比较2个列表并从1个列表中删除包含其他列表子字符串的a字符串?python
如果其他列表包含某个特定字符串的子字符串,是否仍然可以删除该字符串?例如: 列表x包含子字符串,因为y[0]在单词中有“hi”(包含在列表x中),所以我想删除它如何比较2个列表并从1个列表中删除包含其他列表子字符串的a字符串?python,python,compare,Python,Compare,如果其他列表包含某个特定字符串的子字符串,是否仍然可以删除该字符串?例如: 列表x包含子字符串,因为y[0]在单词中有“hi”(包含在列表x中),所以我想删除它 x=["yo",'sup','hi'] y= ['hi-test','test2','test3'] 这是我尝试过的,但我认为我的想法是错误的 x=["yo",'sup','hi'] y= ['hi-test','test2','test3'] list1=[] for namex in x:
x=["yo",'sup','hi']
y= ['hi-test','test2','test3']
这是我尝试过的,但我认为我的想法是错误的
x=["yo",'sup','hi']
y= ['hi-test','test2','test3']
list1=[]
for namex in x:
for namey in y:
if namex in namey:
break
else:
list1.append(namey)
print(list1)
我想得到一个包含“test2”和“test3”的列表。试试看。它遍历
x
,然后检查x中的任何字符串是否是y
中任何字符串的子字符串
x=["yo",'sup','hi']
y= ['hi-test','test2','test3']
for count,letters in enumerate(x):
for letters2 in y:
if letters in letters2:x.pop(count)
print(x)
输出
['yo', 'sup']
如果我没有错,这就是你所期望的:
x=["yo",'sup','hi']
y= ['hi','test2','test3']
list1=[]
for namex in x:
for namey in y:
if namex in namey:
del(y[0])
print(list1.append(y))
这是一个单行列表:
list1 = [y_word for y_word in y
if not any(x_word in y_word for x_word in x)]
通俗地说:
对于y
中的每个短语,检查x
中是否有任何单词在该短语中。如果没有,则将该短语添加到新的列表1
输出:
['test2', 'test3']