【问题标题】:Adding the 2D array list values to a string in python将二维数组列表值添加到python中的字符串
【发布时间】:2020-11-08 14:57:40
【问题描述】:

我正在尝试将 2D 列表转换为 mongodb 文档格式。 以下是我的清单

list1=[('New Mexico', 'NM', '2020-04-06', 686, 12), ('New Mexico', 'NM', '2020-07-07', 13727, 519)]

我想把它转换成下面的格式

{'state':'New Mexico','State_code':'NM','Date':'2020-04-06','cases':686,'deaths':12}

我尝试访问列表但无法获得上述格式 下面是代码

for i in range(len(list1)):
    for j in range(len(list1[i])):
        item={
            'state': list1[i][j],
            'state_code': list1[i][j],
            'date': list1[i][j],
            'cases': list1[i][j],
            'deaths': list1[i][j]
        }            
    print(item)

上面的代码向所有它们插入相同的值,我可以知道如何将每个值插入到它们中(例如 state、state_code 等)

提前致谢

【问题讨论】:

  • “上面的代码向所有它们插入相同的值,我可以知道如何将每个值插入到它们中(例如 state、state_code 等)” - 这是什么意思?添加示例并在问题中清楚说明。

标签: python arrays mongodb list multidimensional-array


【解决方案1】:

您最好分配如下所示的项目。不需要第二个循环。但是,您必须确保 list1 中的所有项目都具有相同的长度,即所有必要的值:

for i in list1:
        item={
            'state': i[0],
            'state_code': i[1],
            'date': i[2],
            'cases': i[3],
            'deaths': i[4]
        }            
    print(item)

【讨论】:

    【解决方案2】:

    您好 sumesh 因为 rads 说您需要保存每次迭代的结果。通过做一个小的改变,你可以得到最终的结果

    items = []
    for i in list1:
        temp_item={
            'state': [i][0],
            'state_code': [i][1],
            'date': [i][2],
            'cases': [i][3],
            'deaths': [i][4]
        }
        items.append(temp_item)            
    print(items)
    

    我只是将每次迭代的结果保存在 temp_item 中,然后将它们附加到项目列表中:)

    【讨论】:

      【解决方案3】:

      您可以使用常规列表推导和zip-

      # Put the keys to associate with the values in order as they appear in the tuples inside list1
      keys = ('state', 'State_code', 'Date', 'cases', 'deaths')
      result = [dict(zip(keys, l)) for l in list1]
      

      输出

      [{'state': 'New Mexico',
        'State_code': 'NM',
        'Date': '2020-04-06',
        'cases': 686,
        'deaths': 12},
       {'state': 'New Mexico',
        'State_code': 'NM',
        'Date': '2020-07-07',
        'cases': 13727,
        'deaths': 519}]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多