排除具有空值的 Python 列表 (Excluding Python Lists With Empty Values)


問題描述

排除具有空值的 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.

(by nia4lifeJJ Hassan)

參考文件

  1. Excluding Python Lists With Empty Values (CC BY‑SA 2.5/3.0/4.0)

#conditional-statements #if-statement #Python #python-3.x #list






相關問題

在 SSRS 中使用條件來提高可見性 (using conditionals in SSRS for visibility)

Smarty - {IF} {/IF} 內的條件太多 (Smarty - Too many conditions inside {IF} {/IF})

awk 如果有多個條件拋出錯誤 (awk if with multiple condition throws error)

正則表達式錯誤,嵌套標籤 (Regex error, nested tags)

警告:分配條件 (Warning: Assignment in condition)

JavaScript 中的條件語句 (Conditional Statement in JavaScript)

與 linus 條件 '-z' '-n' 混淆 (Confuse with the linus conditions '-z' '-n')

如果條件為真,則將表達式添加到循環中 (if condition is true, add an expression to a loop)

為什麼用多態性替換條件有用? (Why is replacing conditionals with polymorphism useful?)

如何使用條件將一個數據框列的值與另一個數據框列的值匹配? (How do you match the value of one dataframe's column with another dataframe's column using conditionals?)

使用另一個數據框的條件創建一個新列 (Create a new column with a condition of another dataframe)

排除具有空值的 Python 列表 (Excluding Python Lists With Empty Values)







留言討論