python - 使用字典在Python中将列表拆分为两部分

标签 python list python-2.7 dictionary split

我想像这样拆分列表

[{'Age': '23', 'Name': 'John'}, {'Age': '43', 'Name': 'Apple'}, {'Age': '13', 'Name': 'Alice'}]

这是我的代码

temp_list=["John","Apple","Alice","23","43","13"]
temp_dict={'Name':'','Age':''}
final_list=[]
for temp in temp_list:
    temp_dict['Name']=temp
    temp_dict['Age']=temp
    final_list.append(temp_dict)
    temp_dict={'Name':'','Age':''}
print final_list

我该怎么办?

最佳答案

您可以使用以下字典理解:

 final_list = dict(zip(temp_list[:3], temp_list[3:]))

示例:

>>> temp_list=["John","Apple","Alice","23","43","13"]
>>> final_list = dict(zip(temp_list[:3], temp_list[3:]))
>>> final_list
{'John': '23', 'Apple': '43', 'Alice': '13'}

一般来说,如果n = len(temp_list),您可以使用:

final_list = dict(zip(temp_list[:n // 2], temp_list[n // 2:]))

关于python - 使用字典在Python中将列表拆分为两部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29946106/

相关文章:

QtWebKit 中的 JavaScript 和异步方法

c# - 使用 List.Move 将项目移动到列表底部

没有 "direct access"的 Java ArrayList

python-2.7 - Python,从运行命令获取状态

python pptx改变整个表格的字体大小

javascript - 无法在页面中找到元素。检查元素显示与源页面不同的 HTML Python - Selenium

python - 将包含多行 JSON 的文件加载到 Pandas 中

language-agnostic - 有索引链表的已知实现吗?

python-2.7 - 如何在ubuntu中完全卸载python并重新安装?

Python 解码/编码问题