The python implementation divides the given list into two sublists whose elements are roughly equal

Assuming that there is an existing list [300,150,75,38,19,9,5,2], I want to divide it into two sub-lists, and require the sum of the elements of the two lists to be roughly equal, how should I do it?

This is a very interesting question, and the answer we expect should be:

list1: [300]
list2: [150,75,38,19,9,5,2]

Before writing this blog, I have browsed Together_CZ's answer . His idea is: when the difference between the element and the larger list and the element and the smaller list is greater than the smallest element in the element and the larger list, you need Pop the smallest element to join the element and the smaller list.

But the answer is actually to redistribute the list, rather than "dividing". If I just want to split a list into two sublists with roughly equal elements and keep the order of the elements unchanged , what should I do? In fact, only a few minor changes are required.

def list_split(one_list):
    ''' 将给定的列表划分为元素和大致相当的两个子列表 '''
    num_list = copy.deepcopy(one_list[:]) # 原列表深拷贝
    first_list = [] # 列表构建
    second_list = [] # 列表构建

    # ------ 将原列表划分为元素和大致相对的两个子列表 ------ #
    first_list.append(num_list.pop(0)) # 列表初始化
    second_list.append(num_list.pop(-1)) # 列表初始化
    while len(num_list) != 0: # 若原列表中还有元素
        if sum(first_list) >= sum(second_list): # 若first列表中元素和大于second列表
            second_list.insert(0, num_list.pop(-1)) # 在头部插入
        else:
            first_list.append(num_list.pop(0)) # 在尾部添加

    return first_list, second_list # 返回

if __name__ == "__main__":
	first_list, second_list = list_split([300,150,75,38,19,9,5,2])
	print(first_list)
	print(second_list)

output:

[300]
[150,75,38,19,9,5,2]

As you can see, the order of the sublists is the same as in the original list.

Try again with a list with smaller intervals between element values:

# 代码:
first_list, second_list = list_split([300, 299, 298, 297, 296, 295, 294, 293])
print(first_list)
print(second_list)

# 输出:
[300, 299, 298, 297]
[296, 295, 294, 293]

Try again with an unordered list:

first_list, second_list = list_split([3, 12, 5, 9, 1, 7, 4])
print(first_list)
print(second_list)

# 输出:
[3, 12, 5]
[9, 1, 7, 4]

Guess you like

Origin blog.csdn.net/baishuiniyaonulia/article/details/130225730