基于多个条件筛选列表

2024-03-29 07:02:06 发布

您现在位置: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"
]

程序应允许用户:

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

下面是对我的想法的模仿,我确信一定有一个更好的模式,比如map、filter、reduce,甚至是内置的filter,所以希望能对如何改进有所帮助。程序将接受和用户输入,并且仅在指定筛选器类型时进行筛选。例如,列出物品的清单—排除地区nz—运输船。你知道吗

我的模拟尝试

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)

Tags: oftruereturnifdeffilterelsefilters
3条回答

您可以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(lambda x: airports_excluding_nz(x) , list_of_stuff) ) )
print ("all regions in aus:", 
       ", ".join( filter(lambda x: airports_in_aus(x) , list_of_stuff) ) )
print ("all ships:", 
       ", ".join( filter(lambda x: ships(x) , 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

您可以使用三种直接的列表理解:

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

splits = list(map(lambda x: x.split('-'), lst))

lst1 = [x for x in splits if x[1] == 'airport' and x[0] != 'nz']
print(f'All airports excluding nz: {lst1}')

lst2 = [x for x in splits if x[1] == 'airport' and x[0] == 'aus']
print(f'All airports in aus: {lst2}')

lst3 = [x for x in splits if x[1] == 'ship']
print(f'All ships: {lst3}')

这样怎么样:

import argparse 

parser = argparse.ArgumentParser()
parser.add_argument("--exclude-region", dest="excluded_region", action="store")
parser.add_argument("--only-region", dest="only_region", action="store")
parser.add_argument("--transport", dest="transport", action="store")
args_space = parser.parse_args()


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


def exclude_by_country(country, elements):
    return filter(lambda x: x.split('-')[0] != country, elements)

def filter_by_country(country, elements):
    return filter(lambda x: x.split('-')[0] == country, elements)

def filter_by_type(vehicle_type, elements):
    return filter(lambda x: x.split('-')[1] == vehicle_type, elements)


results = list_of_stuff

if args_space.excluded_region:
    results = exclude_by_country(args_space.excluded_region, results)

if args_space.only_region:
    results = filter_by_country(args_space.only_region, results)

if args_space.transport:
    results = filter_by_type(args_space.transport, results)

print([x for x in results])

相关问题 更多 >