确定Python中的所有项目是否相同

时间:2013-10-22 18:57:58

标签: python boolean

我有一个城市列表,每个城市都有一个名称,一个真值或假值,然后是另一个与其连接的城市的列表。如果所有城市都是True而False并非所有城市都是True,我如何在Python中编写一个函数来表示True?

以下是我的城市制作方式:

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

3 个答案:

答案 0 :(得分:5)

我相信你只想要all()

all(city.bool_value for city in city_list)

  

all迭代的的

     

如果 iterable 的所有元素都为true(或者iterable为空),则返回True。相当于:

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

2.5版中的新功能。

答案 1 :(得分:2)

使用内置all

all(city.isTrue for city in city_list)

答案 2 :(得分:0)

我不确切知道哪个变量包含3个项目列表,但基本上是:

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

列表理解只是抓取所有布尔值,如果所有项都为真,则all对于iterable返回true。

编辑:更改为生成器表单。