Python-IZIP列表理解返回空lis

2024-06-01 12:41:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个正在排序的字符串列表。在我用来排序的列表中有12个不同的键字符串。因此,我不想编写12个单独的列表理解,而是使用一个空列表列表和一个键字符串列表来排序,然后使用izip来执行列表理解。以下是我正在做的:

>>> 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'>)

为什么这个进程返回空列表?你知道吗


Tags: 字符串in列表for排序typelineitem
2条回答

看起来您正试图在压缩变量x之后将其填充回tran\u列表中,但是izip只保证返回的类型是迭代器,而不是返回原始列表的严格指针。在for循环中,您可能会丢失正在进行的所有工作,而没有意识到这一点。你知道吗

变量很像贴纸。

可以在同一物体上放置多个贴纸:

>>> 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没有连接。你知道吗

相关问题 更多 >