首页 > 解决方案 > 以列表的形式将一个列表中的 1/2 元素附加到另一个列表中

问题描述

我有一个这样的列表:

lst = [{1, 2, 3, 4, 5, 6}, {15, 19, 16, 21, 20, 45, 78}]

我想创建两个这样的新列表:

first_half = [{1, 2, 3}, {19, 15, 16}]
second_half = [{4, 5, 6}, {45, 21, 78, 20}]

我尝试了这样的事情:

first_half_list = []
second_half_list = []
first_half = []
second_half = []
for i in range(len(lst)):
    set2list = list(lst[i])
    print(set2list)
    for j in range(len(set2list)):
        if j < (len(set2list)//2):
            first_half_list.append(set2list[j])
        else:
            second_half_list.append(set2list[j])
    first_half.append(set(first_half_list))
    second_half.append(set(second_half_list))
    print(first_half, '\n')

但我得到了一个奇怪的结果:

在此处输入图像描述

非常感谢任何建议或帮助。谢谢!

标签: pythonlistsetnested-lists

解决方案


您可以使用列表推导获得所需的结果,将集合转换为列表以便您可以对它们进行切片,然后将结果列表转换回集合:

lst = [{1, 2, 3, 4, 5, 6}, {15, 19, 16, 21, 20, 45, 78}]

first_half = [set(list(s)[:len(s)//2]) for s in lst]
second_half = [set(list(s)[len(s)//2:]) for s in lst]

print(first_half, second_half, sep='\n')

输出:

[{1, 2, 3}, {45, 78, 15}]
[{4, 5, 6}, {16, 19, 20, 21}]

推荐阅读