我如何编写一个函数,将餐厅列表作为参数,并且 returns 仅包含未关闭的餐厅列表?

how can i write a function that takes in a list of restaurants as an argument and returns a list of only the restaurants that are not closed?

fork_fig = {'categories': [{'alias': 'burgers', 'title': 'Burgers'},
  {'alias': 'sandwiches', 'title': 'Sandwiches'},
  {'alias': 'salad', 'title': 'Salad'}],
 'coordinates': {'latitude': 35.10871, 'longitude': -106.56739},
 'display_phone': '(505) 881-5293',
 'distance': 3571.724649307866,
 'id': 'fork-and-fig-albuquerque',
 'image_url': 'https://s3-media1.fl.yelpcdn.com/bphoto/_-DpXKfS3jv6DyA47g6Fxg/o.jpg',
 'is_closed': False,
 'location': {'address1': '6904 Menaul Blvd NE',
  'address2': 'Ste C',
  'address3': '',
  'city': 'Albuquerque',
  'country': 'US',
  'display_address': ['6904 Menaul Blvd NE', 'Ste C', 'Albuquerque, NM 87110'],
  'state': 'NM',
  'zip_code': '87110'},
 'name': 'Fork & Fig',
 'phone': '+15058815293',
 'price': '$$',
 'rating': 4.5,
 'review_count': 604}

frontier_restaurant = {'categories': [{'alias': 'mexican', 'title': 'Mexican'},
  {'alias': 'diners', 'title': 'Diners'},
  {'alias': 'tradamerican', 'title': 'American (Traditional)'}],
 'coordinates': {'latitude': 35.0808088832532, 'longitude': -106.619402244687},
 'display_phone': '(505) 266-0550',
 'distance': 4033.6583235266075,
 'id': 'frontier-restaurant-albuquerque-2',
 'image_url': 'https://s3-media4.fl.yelpcdn.com/bphoto/M9L2z6-G0NobuDJ6YTh6VA/o.jpg',
 'is_closed': True,
 'location': {'address1': '2400 Central Ave SE',
  'address2': '',
  'address3': '',
  'city': 'Albuquerque',
  'country': 'US',
  'display_address': ['2400 Central Ave SE', 'Albuquerque, NM 87106'],
  'state': 'NM',
  'zip_code': '87106'},
 'name': 'Frontier Restaurant',
 'phone': '+15052660550',
 'price': '$',
 'rating': 4.0,
 'review_count': 1369}

我有两个如上所述的餐厅列表,我想使用条件循环使 return 仅包含未关闭的餐厅的列表。

restaurants = [fork_fig, frontier_restaurant]

open_restaurants(restaurants)[0]['name'] ###I want restaurant name to be appear

下面是我一直在处理的代码,我不太确定如何解决这个问题以获得我想要的值 return。

def open_restaurants(restaurants):
    selected = []
    for i in restaurants:
        if fork_fig['is_closed']: 
            selected = restaurants[1]
        else:
            selected = restaurants[0]

    return selected

接评论:

fork_fig = {'categories': [{'alias': 'burgers', 'title': 'Burgers'},
  {'alias': 'sandwiches', 'title': 'Sandwiches'},
  {'alias': 'salad', 'title': 'Salad'}],
 'coordinates': {'latitude': 35.10871, 'longitude': -106.56739},
 'display_phone': '(505) 881-5293',
 'distance': 3571.724649307866,
 'id': 'fork-and-fig-albuquerque',
 'image_url': 'https://s3-media1.fl.yelpcdn.com/bphoto/_-DpXKfS3jv6DyA47g6Fxg/o.jpg',
 'is_closed': False,
 'location': {'address1': '6904 Menaul Blvd NE',
  'address2': 'Ste C',
  'address3': '',
  'city': 'Albuquerque',
  'country': 'US',
  'display_address': ['6904 Menaul Blvd NE', 'Ste C', 'Albuquerque, NM 87110'],
  'state': 'NM',
  'zip_code': '87110'},
 'name': 'Fork & Fig',
 'phone': '+15058815293',
 'price': '$$',
 'rating': 4.5,
 'review_count': 604}

frontier_restaurant = {'categories': [{'alias': 'mexican', 'title': 'Mexican'},
  {'alias': 'diners', 'title': 'Diners'},
  {'alias': 'tradamerican', 'title': 'American (Traditional)'}],
 'coordinates': {'latitude': 35.0808088832532, 'longitude': -106.619402244687},
 'display_phone': '(505) 266-0550',
 'distance': 4033.6583235266075,
 'id': 'frontier-restaurant-albuquerque-2',
 'image_url': 'https://s3-media4.fl.yelpcdn.com/bphoto/M9L2z6-G0NobuDJ6YTh6VA/o.jpg',
 'is_closed': True,
 'location': {'address1': '2400 Central Ave SE',
  'address2': '',
  'address3': '',
  'city': 'Albuquerque',
  'country': 'US',
  'display_address': ['2400 Central Ave SE', 'Albuquerque, NM 87106'],
  'state': 'NM',
  'zip_code': '87106'},
 'name': 'Frontier Restaurant',
 'phone': '+15052660550',
 'price': '$',
 'rating': 4.0,
 'review_count': 1369}


restaurants = [fork_fig, frontier_restaurant]  

def open_restaurants(restaurants):
    selected = []
    for i in restaurants:
        if 'is_closed' in i:
            if not i['is_closed']:
                selected.append(i['name'])
    return selected

print(open_restaurants(restaurants))

输出:

['Fork & Fig']

较短版本:

使用列表理解:

def open_restaurants(restaurants):
    return [x['name'] for x in restaurants if 'is_closed' in x and not x["is_closed"]]

print(open_restaurants(restaurants))

使用 get() 而不是索引:

def open_restaurants(restaurants):
    return [x['name'] for x in restaurants if 'name' in x and not x.get('is_closed', True)]

print(open_restaurants(restaurants))

使用filter函数:

def open_restaurants(restaurants):
    return filter(lambda r: not r['is_closed'], restaurants)

在这里使用列表理解。一行且易于阅读

open_restaurants = [restaurant.get("name") for restaurant in restaurants if not restaurant.get("is_closed")]

Output: ["Fork & Fig"]


有一种简单的方法可以将所有开放的餐厅附加到一个新列表并打印它们的名称。 您将需要两个循环来完成此操作。

操作方法如下:

restaurants = [fork_fig, frontier_restaurant] # a list of restaurants
def open_restaurants(restaurants):
    selected = [] 
    for i in restaurants:  # append all open restaurants to a new list
        if not i['is_closed']:
            selected.append(i)
    return selected

my_open_restaurants = open_restaurants(restaurants) # call the function

for rest in my_open_restaurants:  # print all the names
    print(rest['name'])     

在您的示例中,输出将是:Fork & Fig