【问题标题】:Python IZIP list comprehension returns empty listPython IZIP 列表理解返回空列表
【发布时间】:2014-08-28 13:01:03
【问题描述】:

我有一个正在排序的字符串列表。我用来排序的列表中有 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'>)

为什么这个进程返回空列表?

【问题讨论】:

    标签: python izip


    【解决方案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 无关。

    【讨论】:

      【解决方案2】:

      看起来您正试图将变量 x 压缩后填充回 tran_list,但 izip 仅保证返回的类型是迭代器,而不是返回原始列表的严格指针。您可能在不知不觉中丢失了您在 for 循环中所做的所有工作。

      【讨论】:

        猜你喜欢
        • 2017-04-01
        • 1970-01-01
        • 2017-02-27
        • 2023-04-08
        • 1970-01-01
        • 2017-03-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多