Python IZIP list comprehension返回空列表
问题描述:
我有我正在排序的字符串列表。列表中有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'>)
为什么此过程返回空列表?
答
变量很像贴纸。
你可以有置于同样的事情多贴:
>>> 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
没有任何关系。
答
看起来你试图在变量x被压缩后将变量x回填到tran_list中,但是izip只保证返回的类型是一个迭代器,而不是它是一个严格的指针回到原始列表。您可能会失去在for循环内执行的所有工作而不会意识到这一点。