alex
alex

Reputation: 2541

Python get items in a list of that are not in a list

I have a list with countries: countries = ['United States', 'Canada', 'France', 'Japan', 'Turkey', 'Germany', 'Ghana', 'Hong Kong', 'United Kingdom']

i want to get all the lines that do not contain any country. this is my code:

with open('file.txt') as f:
    lines = f.readlines()[1:5]
    a = [line.split(':') for line in lines]
    for country in countries:
        for line in a:
            if country not in line:
                print(line)

print(line) prints all the lines instead of printing those that do not contain countries

Upvotes: 4

Views: 90

Answers (2)

Ajax1234
Ajax1234

Reputation: 71451

You can try this:

data = [i.strip('\n').split(":") for i in open('filename.txt')]
countries = ['United States', 'Canada', 'France', 'Japan', 'Turkey', 'Germany', 'Ghana', 'Hong Kong', 'United Kingdom']
final_data = [i for i in data if not any(b in countries for b in i)]

Upvotes: 1

Tim Pietzcker
Tim Pietzcker

Reputation: 336188

That's what the any() and all() functions are for.

countries = ['United States', 'Canada', 'France', 'Japan', 'Turkey', 'Germany', 'Ghana', 'Hong Kong', 'United Kingdom']
with open('file.txt') as f:
    lines = f.readlines()[1:5]
    a = [line.split(':') for line in lines]
    for line in a:
        if not any(country in line for country in countries):
            print(line)

Upvotes: 7

Related Questions