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

时间:2017-10-27 13:19:32

标签: python

我有一个国家列表: 国家= ['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 country in countries:
        for line in a:
            if country not in line:
                print(line)

print(line)打印所有行,而不是打印那些不包含国家/地区的行

2 个答案:

答案 0 :(得分:7)

这就是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)

答案 1 :(得分:1)

你可以试试这个:

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