Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
78 views
in Technique[技术] by (71.8m points)

How to remove the matched values in two lists separately in python?

I am facing a issue with my for loop in respect to lists. I have two lists like shown below. Now I want to remove the name if the name in both lists matches. My code

Input:
 col = ['cat','dog','bird','fish']
col_names= [cat,bird]
r=[]
for i in col:
    print(i)
    if i in col_names: col_names.remove(i)
    r.append(col_names)
print(r)

then I am getting an output like this

r = [['dog','fish']] [['dog','fish']]

What I want is:

r =['dog','bird','fish'] ['cat','dog','fish']
question from:https://stackoverflow.com/questions/65933571/how-to-remove-the-matched-values-in-two-lists-separately-in-python

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Simpler way to achieve this is using nested list comprehension :

>>> col = ['cat','dog','bird','fish']
>>> col_names= ['cat', 'bird']

>>> [[c for c in col if c !=cn] for cn in col_names]
[['dog', 'bird', 'fish'], ['cat', 'dog', 'fish']]

The code you shared is not logically correct. If you want to do it with explicit for loop, you can write it like this:

new_list = []
for cn in col_names:
    temp_list = []
    for c in col:
        if c != cn:
            temp_list.append(c)
    new_list.append(temp_list)

print(new_list)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...