問題描述
排除具有空值的 Python 列表 (Excluding Python Lists With Empty Values)
我有兩個列表,如果列表有數據,我想創建一個變量並為其分配一個名稱。如果沒有,我想無視它。然後我想將列表名稱合併到一個列表中。
如果列表中沒有數據,我很難返回空值。
countries = ['America', 'France']
cities = []
if len(countries) != 0:
country_name = 'country'
else:
country_name = None
if len(cities) != 0:
city_name = 'city'
else:
city_name = None
region_names = [country_name, city_name]
獲取:
['country', None]
想要:
['country']
參考解法
方法 1:
The reason this isn't working the way you want is None
is still a NoneType object. So you can have a list of NoneType
objects, or NoneType
objects mixed with other types such as strings in your example.
If you wanted to keep the structure of your program similar, you could do something like
countries = ['America', 'France']
cities = []
region_names = []
if len(countries) != 0:
region_names.append('country')
if len(cities) != 0:
region_names.append('city')
in this example we declare region_names
up front and only append to the list when our conditions are met.