【问题标题】:My Python module returns wrong list我的 Python 模块返回错误列表
【发布时间】:2015-10-09 23:53:53
【问题描述】:

我完成了以下 Python 脚本,它应该返回一个子列表列表。

def checklisting(inputlist, repts):
result = []
temprs = []
ic = 1;
for x in inputlist
    temprs.append(x)
    ic += 1
    if ic == repts:
        ic = 1
        result.append(temprs)
return result

示例:如果我使用以下参数调用函数:

checklisting(['a', 'b', 'c', 'd'], 2)

它会返回

[['a', 'b'], ['c', 'd']]

或者如果我这样称呼它:

checklisting(['a', 'b', 'c', 'd'], 4)

它会返回

[['a', 'b', 'c', 'd']]

然而它返回的是一个奇怪的巨大列表:

    >>> l.checklisting(['a','b','c','d'], 2)
[['a', 'b', 'c', 'd'], ['a', 'b', 'c', 'd'], ['a', 'b', 'c', 'd'], ['a', 'b', 'c', 'd']]

请有人帮忙!我需要该脚本来编译包含数据的列表:

['water tax', 20, 'per month', 'electric tax', 1, 'per day']

其背后的逻辑是将列表中 repts 大小的序列分隔为子列表,以便更好、更容易地组织。我不想要任意的子列表块,因为其他问题中的这些子列表没有正确指定序列的大小。

【问题讨论】:

标签: python list return


【解决方案1】:

你的逻辑有缺陷。

以下是错误:您不断追加到temprs。一旦达到repts,您需要从temprs 中删除元素。另外,list indexes 从 0 开始,所以 ic 应该是 0 而不是 1

将您的 def 替换为:

def checklisting(inputlist, repts):
    result = []
    temprs = []
    ic = 0;
    for x in inputlist:
        temprs.append(x)
        ic += 1
        if ic == repts:
            ic = 0
            result.append(temprs)
            temprs = []

    return result

Here 是上述代码工作演示的链接

【讨论】:

    【解决方案2】:
    def split_into_sublists(list_, size):
        return list(map(list,zip(*[iter(list_)]*size)))
    
        #[iter(list_)]*size this creates size time lists, if 
        #size is 3 three lists will be created.
        #zip will zip the lists into tuples
        #map will covert tuples to lists.
        #list will convert map object to list.
    
    print(split_into_sublists(['a', 'b', 'c', 'd'], 2))
    
        [['a', 'b'], ['c', 'd']]
    
    print(split_into_sublists(['a', 'b', 'c', 'd'], 4))
    
    [['a', 'b', 'c', 'd']]
    

    【讨论】:

    • 虽然这个答案可能是正确的,但请添加一些解释。传递底层逻辑比仅仅提供代码更重要,因为它可以帮助 OP 和其他读者自己解决这个问题和类似问题。
    • 哦,谢谢!我真的很喜欢那个。对不起,无法解释。我通过示例尽了最大努力...
    【解决方案3】:

    我迷失在你的代码中。我认为更 Pythonic 的方法是对列表进行切片。而且我永远无法抗拒列表推导。

    def checklisting(inputlist, repts):
        return [ input_list[i:i+repts] for i in range(int(len(input_list)/repts)) ]
    

    【讨论】:

      猜你喜欢
      • 2023-02-24
      • 2013-09-05
      • 2013-11-29
      • 2011-06-23
      • 2014-08-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多