Python gets items in a list that are not on the 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 rows 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 lines instead of printing those that do not contain countries

+4
source share
2 answers

What is that any()and all()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)
+7
source

You can try the following:

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)]
+1
source

Source: https://habr.com/ru/post/1688295/


All Articles