2014-08-28 82 views
0

我有我正在排序的字符串列表。列表中有12個不同的關鍵字符串用於排序。因此,我不想編寫12個單獨的列表解析,而是使用空列表和關鍵字符串列表進行排序,然後使用izip執行列表解析。下面是我在做什麼:Python IZIP list comprehension返回空列表

>>> from itertools import izip 
>>> tran_types = ['DDA Debit', 'DDA Credit'] 
>>> tran_list = [[] for item in tran_types] 
>>> trans = get_info_for_branch('sco_monday.txt',RT_NUMBER) 
>>> for x,y in izip(tran_list, TRANSACTION_TYPES): 
    x = [[item.strip() for item in line.split(' ') if not item == ''] for line in trans if y in line] 
>>> tran_list[0] 
[] 

我想看到的輸出更像是以下幾點:

>>> tran_list[0] 
[['DDA Debit','0120','18','3','83.33'],['DDA Debit','0120','9','1','88.88']] 

輸出沒有道理給我; izip返回的對象是列表和字符串

>>> for x,y in itertools.izip(tran_list, TRANSACTION_TYPES): 
type(x), type(y) 
(<type 'list'>, <type 'str'>) 
(<type 'list'>, <type 'str'>) 

爲什麼此過程返回空列表?

回答

1

變量很像貼紙。

你可以有置於同樣的事情多貼:

>>> a=b=[]  #put stickers a and b on the empty list 
>>> a.append(1) #append one element to the (previously) empty list 
>>> b   #what's the value of the object the b sticker is attached to? 
[1] 

,可以有東西,有沒有貼紙可言:

>>> a=[1,2,3] 
>>> a=""   #[1,2,3] still exists 

雖然他們不是非常有用的,因爲你不能引用他們 - 所以他們最終garbage collected


>>> for x,y in izip(tran_list, TRANSACTION_TYPES): 
    x = [[item.strip() for item in line.split(' ') if not item == ''] for line in trans if y in line] 

在這裏,你必須在它x貼紙。當您分配(x=...)時,您正在更改貼紙的位置 - 不會修改貼紙最初放置的位置。

您正在分配一個變量,而該變量又被分配給每次for循環循環。 您的任務完全沒有效果。

對於python中的任何類型的for循環都是如此,尤其是與izip沒有任何關係。

-1

看起來你試圖在變量x被壓縮後將變量x回填到tran_list中,但是izip只保證返回的類型是一個迭代器,而不是它是一個嚴格的指針回到原始列表。您可能會失去在for循環內執行的所有工作而不會意識到這一點。