2013-10-22 28 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

相關問題