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
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)
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)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With