以列表的形式将一个列表中的1/2元素附加到另一个列表中

2024-09-28 20:41:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这样一份清单:

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

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

enter image description here

我们非常感谢您的任何建议或帮助。谢谢


Tags: 方法in列表forlenrangelistfirst
3条回答

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

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

由于集合不可下标,我们应该将它们转换为列表,然后再将它们转换回集合

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

for i in lst:
    i = list(i)
    a_lst.append(set(i[:len(i) // 2]))
    b_lst.append(set(i[len(i) // 2:]))

print(a_lst)
print(b_lst)

输出

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

正如其他人所解释的,您需要将集合转换为列表,以便可以对它们进行切片 下面是根据您的期望结果工作的示例,但是您通过研究列表理解来优化此示例并使其通用

lst = [{1, 2, 3, 4, 5, 6}, {15, 19, 16, 21, 20, 45, 78}]
a = list(lst[0])
b=list(lst[1])

first_elm = set(a[0:int(len(a)/2)])
sec_elem = set(b[0:int(len(b)/2)])
third_elem = set(a[int(len(a)/2):])
fourth_elem = set(b[int(len(b)/2):])

first_half = list([first_elm,sec_elem] )
first_half
second_half = list([third_elem,fourth_elem] )
second_half

相关问题 更多 >