首页 > 解决方案 > 根据条件在列表中形成组

问题描述

(根据反馈编辑)

我有一个这样的列表:

my_list = [1,2,3,1,2,4,1,3,5,1,4,6,1,4,7]

我正在努力变成这样:

result = [[1,2,3,1,2,4],[1,3,5],[1,4,6,1,4,7]]

我想将 my_list 元素分组到 3 个元素的子列表中,除非 my_list[i] = my_list[i+3] 在这种情况下我想将它们合并到更大的子列表中。

这是我尝试过的:

result = []
for i in range(1,len(my_list),3):
    try:
        print(my_list[i],my_list[i+3])

        if my_list[i] == my_list[i+3]:
           result.extend(my_list[i-1:i+5])
    else:
        result.append(my_list[i-1:i+2])

标签: pythonlistconditional-statements

解决方案


FWIW,您的逻辑描述不太清楚。但是,如果我正确理解您的代码,我认为这至少是正确的方向:

def stepper(my_list, step, bigger_step):
    res = []
    idx = 0
    while idx <= len(my_list)-1:
        if idx + step > len(my_list)-1:
            # Remove this append if you don't want the "leftovers"
            res.append(my_list[idx:])
            break

        if my_list[idx] != my_list[idx+step]:
            res.append(my_list[idx:idx+step])
            idx += step
        else:
            res.append(my_list[idx:idx+bigger_step])
            idx += bigger_step

    return res

my_list = [1,2,3,1,2,4,1,3,5,1,3,6,1,2,7]
print(stepper(my_list, step=3, bigger_step=6)) # Output: [[1, 2, 3, 1, 2, 4], [1, 3, 5, 1, 3, 6], [1, 2, 7]]

请注意,上述输出与您给定的示例不同,因为您提供的给定逻辑使第二个子列表和第一个子列表一样扩展。

使用上面的代码,如果我们bigger_step使用 for 循环轻松更改,我们可以检查结果:

for big in range(4, 10):
    print(f"Step: 3, Bigger_Step: {big}, Result:{stepper(my_list, step=3, bigger_step=big)}")

输出:

Step: 3, Bigger_Step: 4, Result:[[1, 2, 3, 1], [2, 4, 1], [3, 5, 1, 3], [6, 1, 2], [7]]
Step: 3, Bigger_Step: 5, Result:[[1, 2, 3, 1, 2], [4, 1, 3], [5, 1, 3], [6, 1, 2], [7]]
Step: 3, Bigger_Step: 6, Result:[[1, 2, 3, 1, 2, 4], [1, 3, 5, 1, 3, 6], [1, 2, 7]]
Step: 3, Bigger_Step: 7, Result:[[1, 2, 3, 1, 2, 4, 1], [3, 5, 1, 3, 6, 1, 2], [7]]
Step: 3, Bigger_Step: 8, Result:[[1, 2, 3, 1, 2, 4, 1, 3], [5, 1, 3], [6, 1, 2], [7]]
Step: 3, Bigger_Step: 9, Result:[[1, 2, 3, 1, 2, 4, 1, 3, 5], [1, 3, 6, 1, 2, 7]]

推荐阅读