Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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

like image 890
alex Avatar asked Jan 30 '23 08:01

alex


2 Answers

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)
like image 77
Tim Pietzcker Avatar answered Feb 16 '23 11:02

Tim Pietzcker


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)]
like image 22
Ajax1234 Avatar answered Feb 16 '23 10:02

Ajax1234