【问题标题】:Filter out region names from a list of countries and regions从国家和地区列表中过滤掉地区名称
【发布时间】:2019-09-07 05:32:53
【问题描述】:

一个列表包含世界上所有国家以及地区、大洲等的名称。除了手动之外,还有更优雅的过滤非国家名称的方法吗?

一种解决方案是手动过滤名称,但这似乎...过于手动?

拉丁美洲和加勒比地区、西非和北美等名称需要在他们自己的列表中。

【问题讨论】:

  • 请添加到目前为止您为这个问题尝试过的代码
  • 欢迎来到 Stack Overflow!请熟悉这些常见问题并重新发布您的问题 -- (1) 我如何提出一个好的问题 - stackoverflow.com/help/how-to-ask -- (2) 如何创建一个最小、完整和可验证的示例 - stackoverflow.com/help/mcve
  • 您需要提供更多详细信息和代码示例,以便有人为您提供帮助。
  • 欢迎来到 SO。请提供一些示例数据,因为您提供的描述中不清楚。

标签: python-3.x pandas dataframe


【解决方案1】:

您好,欢迎来到 Stackoverflow。

假设您的列表名为my_list

使用pycountry 包:

import pycountry

coutries = []

for country in list(pycountry.countries):
    countries.append(country)  # Creates a list full of official country names

# Print all the names which are not in countries but are un my_list
print([country for country not in countries and country in my_list])

【讨论】:

  • 谢谢,您回复的第一部分加上以下内容使我得到了预期的结果:regions_not_in_countries_list = countries.symmetric_difference(regions_not_in_countries_list).intersection(regions_not_in_countries_list)
  • 感谢您的反馈,您能否投票并将我的答案标记为解决方案?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多