1

this is my python code

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)

from that code i get result like this

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']]

i want to change result of rawdata like this

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

and like this

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

please help me to fix this code. thank you

Zmx Atah
  • 85
  • 1
  • 7

2 Answers2

1

If need nested lists use zip with convert to nested lists in list comprehension:

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

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

out1 = [list(x) for x in zip(dataheader, databody)]

Instead all your loops is possible use:

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

If need sets:

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

Or if need one element dictionaries in list:

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'}]    

If need all element dictionary:

out4 = dict(zip(head[11:], body[11:]))
print (out4)
{'2020/06/20': '6', '2020/07/20': '7', '2020/08/20': '8'}
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
  • thank you, this code work for me. you save my time. but i get error on ```dict(x)``` _TypeError: cannot convert dictionary update sequence element #0 to a sequence_ – Zmx Atah Nov 14 '20 at 06:54
  • 1
    @ZmxAtah - My bug, need add `[]` like `dict([x]) ` – jezrael Nov 14 '20 at 06:58
1

You need to use a set for the items in your list:

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)

Output:

[{'2020/06/20', '6'}, {'2020/07/20', '7'}, {'2020/08/20', '8'}]
Serial Lazer
  • 1,667
  • 1
  • 7
  • 15