2015-01-01 78 views
-2
single_item_arrays = [] 
component_text_ids = [] 

def getText_identifiers(component_id) : 
    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) 

結果是陣列保持爲空

[] 
['Formfactor', 'PSU'] 

我想,如果發生狀況的陣列應該創建,這樣被刮掉的數據,多數民衆贊成將放在兩個不同的陣列。

我試了幾件事情仍然無法從創建陣列內部函數的if語句

+0

什麼是你打算用'single_item_arrays = formaten,PSU =辦[ ],[]'?我解釋它的方式,它總是將一個空列表分配給'single_item_arrays',因爲'formaten'將被分配一個空列表。 – Makoto

+0

這個函數應該檢查使用了什麼參數,並且通過該輸入,它應該使用一個數組中的text_id來獲取來自網站的數據,並且對於每個textid來說,例如所有項目的formfactor都必須放在一個數組中。和另一個陣列中的psu。你知道 – user3660293

+0

這個函數有更多的條件,這只是十個之一。對於每個組件,它具有相同的條件只是不同的text_id和不同的長度 – user3660293

回答

0

你不能做全局變量(single_item_arrayscomponent_text_ids)分配,但是您可以像append地方做改變。

0

通常會皺起眉頭,但如果您在更新版本的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) 
+0

仍然結果相同.. ([],[]) ['Formfactor','PSU'] empty – aerokite

+0

等等,那些結果不是相同。之前,OP得到[] ['Formfactor','PSU'],現在他得到[[],[]] ['Formfactor','PSU']。你實際上期待什麼作爲輸出? – zehnpaard