简体   繁体   English

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

[英]Determine if all Items are same in Python

I have a list of cities, each city has a name, a true or false value and then another list with cities it is connected to. 我有一个城市列表,每个城市都有一个名称,一个真假值,然后是另一个列表,其中包含与之相连的城市。 How do I write a function in Python to say True if all the cities are True and False is not all of them are True? 如果所有城市均为True和False,但并非所有城市均为True,我该如何在Python中编写一个说True的函数?

Here is how my cities were made: 这是我的城市的组成方式:

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

I believe you simply want all() : 我相信你只是想要all()

all(city.bool_value for city in city_list)

all ( iterable ) all 可迭代

Return True if all elements of the iterable are true (or if the iterable is empty). 如果iterable的所有元素都为true(或者iterable为空),则返回True。 Equivalent to: 相当于:

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

New in version 2.5. 2.5版中的新功能。

使用内置的all

all(city.isTrue for city in city_list)

i don't know exactly which variable holds the 3-item list, but basically: 我不知道到底哪个变量保存着3项列表,但基本上是:

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

the list comprehension just grabs all the booleans, and all returns true for an iterable if all items are true. 列表推导仅获取所有布尔值,并且如果所有项目均为true,则对于可迭代的对象, all返回true。

edit: changed to generator form. 编辑:更改为生成器形式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM