簡體   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