我有这样一份清单:
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')
但我得到了一个奇怪的结果:
我们非常感谢您的任何建议或帮助。谢谢
您可以使用列表理解获得所需的结果,将集合转换为列表,以便对其进行切片,然后将结果列表转换回集合:
输出:
由于集合不可下标,我们应该将它们转换为列表,然后再将它们转换回集合
输出
正如其他人所解释的,您需要将集合转换为列表,以便可以对它们进行切片 下面是根据您的期望结果工作的示例,但是您通过研究列表理解来优化此示例并使其通用
相关问题 更多 >
编程相关推荐