【问题标题】:how make two dimensional array from two variable array in python? [duplicate]如何从python中的两个变量数组制作二维数组? [复制]
【发布时间】:2021-02-26 02:11:21
【问题描述】:

这是我的python代码

dataheader = []
for listhead in head[11:]:
    dataheader.append(listhead)
    
databody = []
for listbody in body[11:]:
    databody.append(listbody)
    
combine = []
for i in range(len(databody)):
     combine.append(str(dataheader[i]))
     combine.append(str(databody[i]))
rawdata = np.reshape(combine, (-1, 2))    
print(rawdata)

从那个代码我得到这样的结果

dataheader = ['2020/06/20', '2020/07/20', '2020/08/20']

databody = ['6', '7', '8']

rawdata = [['2020/06/20' '6'], ['2020/07/20' '7'], ['2020/08/20' '8']]

我想像这样更改原始数据的结果

rawdata = [['2020/06/20', '6'], ['2020/07/20', '7'], ['2020/08/20', '8']]

像这样

rawdata = [{'2020/06/20', '6'}, {'2020/07/20', '7'}, {'2020/08/20', '8'}]

请帮助我修复此代码。谢谢

【问题讨论】:

    标签: python arrays pandas numpy


    【解决方案1】:

    如果需要嵌套列表,请使用 zip 并在列表理解中转换为嵌套列表:

    dataheader = ['2020/06/20', '2020/07/20', '2020/08/20']
    
    databody = ['6', '7', '8']
    
    out1 = [list(x) for x in zip(dataheader, databody)]
    

    您的所有循环都可以使用:

    out1 = [list(x) for x in zip(head[11:], body[11:])]
    

    如果需要的话:

    out2 = [set(x) for x in zip(head[11:], body[11:])]
    

    或者如果需要列表中的一个元素字典:

    out3 = [dict([x]) for x in zip(head[11:], body[11:])]
    print (out3)
    [{'2020/06/20': '6'}, {'2020/07/20': '7'}, {'2020/08/20': '8'}]    
    

    如果需要所有元素字典:

    out4 = dict(zip(head[11:], body[11:]))
    print (out4)
    {'2020/06/20': '6', '2020/07/20': '7', '2020/08/20': '8'}
    

    【讨论】:

    • 谢谢,这段代码对我有用。你节省了我的时间。但我在dict(x) 上遇到错误TypeError: cannot convert dictionary update sequence element #0 to a sequence
    • @ZmxAtah - 我的错误,需要添加 [] 喜欢 dict([x])
    【解决方案2】:

    您需要为列表中的项目使用一个集合:

    dataheader = []
    for listhead in head[11:]:
        dataheader.append(listhead)
        
    databody = []
    for listbody in body[11:]:
        databody.append(listbody)
        
    combine = []
    for i in range(len(databody)):
         temp_set = set()
         temp_set.add(str(dataheader[i]))
         temp_set.add(str(databody[i]))
         combine.append(temp_set)
    
    print(combine)
    

    输出:

    [{'2020/06/20', '6'}, {'2020/07/20', '7'}, {'2020/08/20', '8'}]
    

    【讨论】:

      猜你喜欢
      • 2019-01-11
      • 1970-01-01
      • 1970-01-01
      • 2011-09-25
      • 2012-11-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多