I am having the following input data(temp_list1). I am trying to convert this input into a nested list as mentioned below(new_list). this input is part of vnstat command’s output.
Input:
temp_list1 = [(‘ eno1:’, “rn Oct ’19 10.09 GiB / 68.98 GiB / 79.08 GiB / 164.53 GiBrn yesterday 1.11 GiB / 7.35 GiB / 8.46 GiBrn today 432.51 MiB / 4.22 GiB / 4.65 GiB / 7.17 GiBrnr”), (‘ eno5:’, “rn Oct ’19 18.82 TiB / 18.39 TiB / 37.21 TiB / 77.43 TiBrn yesterday 2.65 TiB / 2.59 TiB / 5.24 TiBrn today 1.95 TiB / 1.90 TiB / 3.85 TiB / 5.95 TiBrnrn”)]
Expected output:
new_list[ ['eno1',["Oct '19",'10.09 GiB','68.98 GiB','79.08 GiB','164.53 GiB'], ["yesterday",'1.11 GiB','7.35 GiB','8.46 GiB'], ["today",'432.51 MiB','4.22 GiB','4.65 GiB','7.17 GiB] ], ['eno5',["Oct '19",'18.82 TiB','18.39 TiB','37.21 TiB','77.43 TiB'], ["yesterday",'2.65 TiB','2.59 TiB','5.24 TiB'], ["today",'1.95 TiB','1.90 TiB','3.85 TiB','5.95 TiB'] ] ]
I am trying to split the input data using the python code but do not know how to do it.
temp_list2 = [] temp_list1 = [(' eno1:', "rn Oct '19 10.09 GiB / 68.98 GiB / 79.08 GiB / 164.53 GiBrn yesterday 1.11 GiB / 7.35 GiB / 8.46 GiBrn today 432.51 MiB / 4.22 GiB / 4.65 GiB / 7.17 GiBrnr"), (' eno5:', "rn Oct '19 18.82 TiB / 18.39 TiB / 37.21 TiB / 77.43 TiBrn yesterday 2.65 TiB / 2.59 TiB / 5.24 TiBrn today 1.95 TiB / 1.90 TiB / 3.85 TiB / 5.95 TiBrnrn")] for i in temp_list1: temp_list2.append i.split('?') print (temp_list2)
Advertisement
Answer
You can try this.
temp_list1 = [(' eno1:', "rn Oct '19 10.09 GiB / 68.98 GiB / 79.08 GiB / 164.53 GiBrn yesterday 1.11 GiB / 7.35 GiB / 8.46 GiBrn today 432.51 MiB / 4.22 GiB / 4.65 GiB / 7.17 GiBrnr"), (' eno5:', "rn Oct '19 18.82 TiB / 18.39 TiB / 37.21 TiB / 77.43 TiBrn yesterday 2.65 TiB / 2.59 TiB / 5.24 TiBrn today 1.95 TiB / 1.90 TiB / 3.85 TiB / 5.95 TiBrnrn")] new_list =[ [ b[0].strip(), [ c.strip().split(" / ") for c in b[1] if c.strip() ]] for b in [[a[0], a[1].split("rn")] for a in temp_list1] ] for a in new_list: for b in a[1]: x = b[0].replace(" '", "'").split() b[0:1] = [x[0].replace("'", " '"), ' '.join(x[1:])] print ( new_list) #Result: # [ # [ 'eno1:',[ # [ "Oct '19", '10.09 GiB', '68.98 GiB', '79.08 GiB', '164.53 GiB'], # [ 'yesterday', '1.11 GiB', '7.35 GiB', '8.46 GiB'], # [ 'today', '432.51 MiB', '4.22 GiB', '4.65 GiB', '7.17 GiB'] # ] # ], # [ 'eno5:',[ # [ "Oct '19", '18.82 TiB', '18.39 TiB', '37.21 TiB', '77.43 TiB'], # [ 'yesterday', '2.65 TiB', '2.59 TiB', '5.24 TiB'], # [ 'today', '1.95 TiB', '1.90 TiB', '3.85 TiB', '5.95 TiB'] # ] # ] # ]