python - 以列表的形式将一个列表中的 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')
但我得到了一个奇怪的结果:
非常感谢任何建议或帮助。谢谢!
解决方案
您可以使用列表推导获得所需的结果,将集合转换为列表以便您可以对它们进行切片,然后将结果列表转换回集合:
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}]
推荐阅读
- silverstripe - Silverstripe has_one CMS 下拉过滤器在 dropdown_field_threshold 之前
- javascript - JavaScript 警报未提供正确的 fileID 值
- javascript - setInterval 的正确放置
- node.js - 如何在不使用 HTML 和 CSS 的情况下将 chart.js 库图表转换为纯 node.js 中的图像?
- java - Hibernate 映射 - 可插入/可更新 = false - 不能设置为空
- hadoop - 从 Teradata 导入 Sqoop - 数据库中没有更多空间
- python - python根据值对字典进行排序
- airflow - Airflow :dag 中的任务具有不同的时间间隔或具有与父 dag 以不同频率运行的 subdag
- windows - 如何在 npm 脚本中为 Windows 和跨平台的 git commit 消息传递当前日期时间?
- java - 我想从 java 程序运行 pict.exe