繁体   English   中英

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

[英]Determine if all Items are same in Python

我有一个城市列表,每个城市都有一个名称,一个真假值,然后是另一个列表,其中包含与之相连的城市。 如果所有城市均为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

我相信你只是想要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版中的新功能。

使用内置的all

all(city.isTrue for city in city_list)

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

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

列表推导仅获取所有布尔值,并且如果所有项目均为true,则对于可迭代的对象, all返回true。

编辑:更改为生成器形式。

暂无
暂无

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

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