【问题标题】:split list two part in python using dictionary使用字典在python中拆分列表两部分
【发布时间】:2015-04-29 14:04:00
【问题描述】:

我想像这样拆分列表

[{'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

我该怎么办?

【问题讨论】:

    标签: python list python-2.7 dictionary split


    【解决方案1】:

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

     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:]))
    

    【讨论】:

      【解决方案2】:

      生成您在问题中指定的结构:

      >>> [dict(zip(("Age", "Name"), x)) for x in zip(temp_list[3:], temp_list[:3])]
      [{'Age': '23', 'Name': 'John'}, {'Age': '43', 'Name': 'Apple'}, {'Age': '13', 'Name': 'Alice'}]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-05-01
        • 1970-01-01
        • 1970-01-01
        • 2019-11-24
        • 1970-01-01
        • 2010-12-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多