我的Python模块返回错误的列表

时间:2015-10-09 23:53:54

标签: python list return

我完成了以下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 的大小的序列分成子列表,这样就可以更好,更轻松地组织起来。我不想要任意的子列表块,因为在另一个问题中没有正确指定序列的大小。

3 个答案:

答案 0 :(得分:2)

你的逻辑是有缺陷的。

以下是错误:您继续追加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是上面代码的工作演示的链接

答案 1 :(得分:1)

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

答案 2 :(得分:0)

我迷失了你的代码。我认为更多的Pythonic方法是切片列表。我永远无法抗拒列表理解。

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