Python 我的代码有什么问题?该文件包含按字母顺序排列的所有国家的列表

Python 我的代码有什么问题?该文件包含按字母顺序排列的所有国家的列表,python,list,Python,List,我的目标是从清单“清单”中删除任何非国家。显然,“蒙斯特”不是一个国家。不过葡萄牙是。为什么它会被移除 checklist = ["Portugal", "Germany", "Munster", "Spain"] def CheckCountry(i): with open("C:/Users/Soham/Desktop/Python Exercises/original.txt",&q

我的目标是从清单“清单”中删除任何非国家。显然,“蒙斯特”不是一个国家。不过葡萄牙是。为什么它会被移除

checklist = ["Portugal", "Germany", "Munster", "Spain"]
def CheckCountry(i):
    with open("C:/Users/Soham/Desktop/Python Exercises/original.txt","r") as f:
        for countries in f.readlines():
            if countries==i:
                continue
            else:
                return True
        return False
for i in checklist:
    if CheckCountry(i)==True:
        index=checklist.index(i)
        checklist.pop(index)
    else:
        CheckCountry(i)
print(checklist)

请告诉我我的代码有什么问题。请记住,我还没有学习regex或lambda。

我认为您在这种情况下不正确地使用了
continue
函数。由于
继续
,您不允许函数进入
返回False
。所以试试这个:

checklist = ["Portugal", "Germany", "Munster", "Spain"]
def CheckCountry(i):
   with open("C:/Users/Soham/Desktop/Python     Exercises/original.txt","r") as f:
      for country in f.readlines():
         if country != i:
            return False
   return True
for i in checklist:
   if CheckCountry(i) == False:
      checklist.pop(checklist.index(i))

print(checklist)
还要记住,python并不要求在
if
之后包含
else
语句。所以在你的情况下,它们只是占据了空间。我不知道你的
.txt
文件是如何设置的,但我假设每行只有一个国家。因为如果每行有多个国家/地区,我建议使用某种单独的列表,以便您可以将每行转换为如下列表:

def CheckCountry(i):
   with open("C:/Users/Soham/Desktop/Python     Exercises/original.txt","r") as f:
      for countries in f.readlines():
         country_lst = countries.split(',') # using , as a separator
         for x in country_lst:
            if x != i:
               return False

这回答了你的问题吗?嗨@Max,即使有你的代码,葡萄牙仍然被排除在名单之外。很奇怪。此外,每行有一个国家/地区。其他人对此有解决方案吗?请检查您的
.txt
文件。代码没有问题,但文件的路径或实际布局可能有问题。