简体   繁体   English

Python在列表中获取不在列表中的项目

[英]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'] 我有一个国家名单:国家= ['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 print(line)打印所有行而不是打印那些不包含国家/地区的行

That's what the any() and all() functions are for. 这就是any()all()函数的用途。

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)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM