简体   繁体   中英

Remove List from List partial match Python

I am trying to remove a list from a list if it has a partial match

List 1

[['Person1', 'www.google.co.uk', '1'], ['Person2', 'www.amazon.co.uk', '2'],['Person3', 'www.google.co.uk', '2']]

List 2

[['Person1', 'www.google.co.uk', '1'], ['Person2', 'www.amazon.co.uk', '2'],['Person1', 'www.google.co.uk', '2']]

Desired Output:

['Person2', 'www.amazon.co.uk', '2']

At the moment I have the following code with will remove it as long as it is a full match:

[i for i in List1 if i in List2]

but as the number can vary i want to be a able to match on the first two entries so it will not matter what number is in the last column

You can do:

l1 = [['Person1', 'www.google.co.uk', '1'], ['Person2', 'www.amazon.co.uk', '2'],['Person3', 'www.google.co.uk', '2']]

l2 = [['Person1', 'www.google.co.uk', '2'], ['Person2', 'www.amazon.co.uk', '2'],['Person1', 'www.google.co.uk', '2']]

print ([ x for x in l1 if x[0:2] in [ l[0:2] for l in l2 ] ])

Output:

[['Person1', 'www.google.co.uk', '1'], ['Person2', 'www.amazon.co.uk', '2']]

Here you check for each sublist in l1 if values at index 0 and 1 are found in [ l[0:2] for l in l2 ] . The later is the same than l2 at the notable exception that it contains only two index by sublist instead of more. So you can use in .

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