首页 > 解决方案 > Python:如何循环列表并附加到新列表

问题描述

下面的列表a打印了 0 到 5 之间的所有项目:

[1, 2, 3, 2, 3]

a = [100, 1, 10, 2, 3, 5, 8, 13, 2, 3, 55, 98]


def new_list(x):
    new = []
    for item in range(len(x)):            

        if x[item] < 5 and x[item] > 0:
            new.append(x[item])
    return new


print new_list(a)

如何打印项目在 0 到 5(含)之间的子列表,如果项目超出范围,则开始一个新的子列表?

预期输出:

[1],[2,3,5],[2,3]

标签: pythonnumpy

解决方案


那你应该再列一张清单。


def new_list(x):
    new = []
    returns = []
    for item in x: # <- I modified the for loop
        if item < 5 and item > 0:
            new.append(item)
        elif len(new) > 0: # <- if out of range and new is not empty
            returns.append(new)
            new = []
    if len(new) > 0: # <- last new check
        returns.append(new)
    return returns

推荐阅读