python - 根据多个条件过滤列表

标签 python

我正在根据下面的列表学习Python,我想根据几个不同的条件进行过滤并组合结果。

list_of_stuff = [
    "aus-airport-1",
    "aus-airport-2",
    "us-airport-1",
    "us-airport-2",
    "aus-ship-1",
    "us-ship-99",
    "nz-airport-1"
]

该程序应该能够允许用户:

  • 打印除新西兰以外的所有地区
  • 打印澳大利亚所有地区
  • 打印所有船只

下面是我的想法的模拟,我确信一定有更好的模式,如映射、过滤器、减少甚至内置过滤器,因此寻求有关如何改进的帮助。该程序将接受用户输入,并且仅在指定过滤器类型的情况下进行过滤。例如 list_of_stuff --exclude_region nz --transport ship。

我的模拟尝试

def filter_transport(stuff,transport):
    if transport:
        if stuff.split("-")[1] == transport:
            return True
        else:
            return False
    else:
        return True    

def exclude_region(stuff,region):
    if region:
        if stuff.split("-")[0] ==region:
            return True
    else:
        return False    

def included_region(stuff,region):
    if region:
        if stuff.split("-")[0] ==region:
            return True
        else:
            return False
    else:
        return True    

def filters(stuff,transport=None,include_region=None,excluded_region=None):
    if( filter_transport(stuff,transport) and 
        included_region(stuff,include_region) and not exclude_region(stuff,excluded_region)  ):
        return True    


#give all airports excluding nz
stuff = [stuff for stuff in list_of_stuff if filters(stuff,transport="airport",excluded_region="nz")]
print (stuff)
#give all airports in aus
stuff = [stuff for stuff in list_of_stuff if filters(stuff,transport="airport",include_region="aus")]
print (stuff)
#give all ships
stuff = [stuff for stuff in list_of_stuff if filters(stuff,transport="ship")]
print (stuff)

最佳答案

您可以filter您的列表:

list_of_stuff = [
    "aus-airport-1",
    "aus-airport-2",
    "us-airport-1",
    "us-airport-2",
    "aus-ship-1",
    "us-ship-99",
    "nz-airport-1"
]

is_airport = lambda x: "-airport-" in x
is_ship = lambda x: "-ship-" in x

airports_excluding_nz = lambda x: is_airport(x) and not x.startswith("nz-")
airports_in_aus = lambda x: is_airport(x) and x.startswith("nz-")
ships = lambda x: is_ship(x)

print ("all regions excluding nz:" , 
       ", ".join( filter(airports_excluding_nz , list_of_stuff) ) )
print ("all regions in aus:", 
       ", ".join( filter(airports_in_aus, list_of_stuff) ) )
print ("all ships:", 
       ", ".join( filter(ships, list_of_stuff) ) )

Check results :

all regions excluding nz aus-airport-1, aus-airport-2, us-airport-1, us-airport-2
all regions in aus nz-airport-1
all ships aus-ship-1, us-ship-99

关于python - 根据多个条件过滤列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53795607/

相关文章:

Python 多项式根不准确

python - 如何根据文本文件创建字典?

python - 动态填充字典

python - 使用 BeautifulSoup4 从网页获取文本时出现 "None"和 'NoneType object...' 错误

python - 冗余函数调用会发生什么?

python - DLL加载失败(无法导入tensorflow)

Python - 如何在 Linux 中的特定 tty 中运行 python 脚本?

python - 我可以将类方法作为默认参数传递给另一个类方法吗

python - 使用 wxPython 强制经典 Windows 主题

python - nltk k-means 聚类或纯 python 的 k-means