2013-10-22 27 views
0

同我有城市的列表,每个城市都有一个名字,一个真或假的值,然后用它连接到其他城市的名单。我如何在Python中编写函数来表示True,如果所有的城市都是True且False不是全部都是True?确定是否所有项目都在Python

下面是我的城市作了:

def set_up_cities(names=['City 0', 'City 1', 'City 2', 'City 3', 'City 4', 'City 5', 'City 6', 'City 7', 'City 8', 'City 9', 'City 10', 'City 11', 'City 12', 'City 13', 'City 14', 'City 15']): 
    """ 
    Set up a collection of cities (world) for our simulator. 
    Each city is a 3 element list, and our world will be a list of cities. 

    :param names: A list with the names of the cities in the world. 

    :return: a list of cities 
    """ 

    # Make an adjacency matrix describing how all the cities are connected. 
    con = make_connections(len(names)) 

    # Add each city to the list 
    city_list = [] 
    for n in enumerate(names): 
     city_list += [ make_city(n[1],con[n[0]]) ] 

    return city_list 
+4

尝试[了'所有()'函数(http://docs.python.org/3/library/functions.html#all)。 – Ryan

+1

我不会用一个列表作为默认参数,肯定不会这么长的一个。 –

回答

5

我相信你只是想all()

all(city.bool_value for city in city_list) 

all迭代

返回真,如果迭代的所有元素都为真(或如果可迭代为空)。相当于:

def all(iterable): 
    for element in iterable: 
     if not element: 
      return False 
    return True 

版本2.5中的新功能。

2

使用内置all

all(city.isTrue for city in city_list) 
0

我不知道哪些变量保存3项列表,但基本上是:

alltrue = all(x[1] for x in all_my_cities) 

列表理解刚刚抓起所有的布尔值,和真正的可迭代all的回报,如果所有项目都是如此。

编辑:改变发电机的形式。

+3

Psst - 删除方括号以创建迭代器。 – Ryan

相关问题