通常會皺起眉頭,但如果您在更新版本的Python中明確聲明變量global
,則可以在技術上從函數內部更改全局變量的賦值。全局變量通常被認爲是bad thing,所以謹慎小心地使用 - 但您也可以將其作爲該語言的一個特徵來了解它。
single_item_arrays = []
component_text_ids = []
def getText_identifiers(component_id) :
global single_item_arrays # Notice the explicit declaration as a global variable
if component_id is 'powersupply':
for i in ['Formfactor','PSU',]:
component_text_ids.append(i)
single_item_arrays = formaten,PSU = [],[]
getText_identifiers('powersupply')
print(single_item_arrays)
print(component_text_ids)
又見Use of "global" keyword in Python
個人而言,我會用以下,具有明確的返回變量代替全局變量:
def getText_identifiers(component_id) :
single_item_arrays, component_text_ids = [], []
if component_id is 'powersupply':
for i in ['Formfactor','PSU',]:
component_text_ids.append(i)
single_item_arrays = formaten,PSU = [],[]
return single_item_arrays, component_text_ids
single_item_arrays, component_text_ids = getText_identifiers('powersupply')
print(single_item_arrays)
print(component_text_ids)
什麼是你打算用'single_item_arrays = formaten,PSU =辦[ ],[]'?我解釋它的方式,它總是將一個空列表分配給'single_item_arrays',因爲'formaten'將被分配一個空列表。 – Makoto
這個函數應該檢查使用了什麼參數,並且通過該輸入,它應該使用一個數組中的text_id來獲取來自網站的數據,並且對於每個textid來說,例如所有項目的formfactor都必須放在一個數組中。和另一個陣列中的psu。你知道 – user3660293
這個函數有更多的條件,這只是十個之一。對於每個組件,它具有相同的條件只是不同的text_id和不同的長度 – user3660293