Home > Blockchain >  How to use loop to reformat lists
How to use loop to reformat lists

Time:04-11

I have expected inputs/outputs as:

(["JS", "SK"], [[200, 400, 500, 600], [400, 1000, 1600]]
->
[['JS', 200, 400, 500, 600], ['SK', 400, 1000, 1600]]


(["JS", "SK", "MJ", "ZF"], [[200, 400, 500, 600], [1010, 2000], [5, 6, 7],
[2660, 500]])
->
[['JS', 200, 400, 500, 600], ['SK', 1010, 2000], ['MJ', 5, 6, 7], ['ZF', 2660, 500]]


(["SK"], [[200, 400]])
->
[['SK', 200, 400]]


(["JS", "SK"]) #only namesList provided
->
None


(paymentList = [[100, 200], [300, 30, 100]])
#only paymentList provided
->
None

I wrote the code to reformat the list correctly however I am having trouble with creating a loop so that it can reformat the list(s) regardless of input.

My code currently is:

firstlst = (["JS", "SK"], [[200, 400, 500, 600], [400, 1000, 1600]])

output = []
for item in firstlst:
    output = [[firstlst[0][0], firstlst[1][0][0],firstlst[1][0][1], firstlst[1][0][2], firstlst[1][0][3]]]
print(output)

CodePudding user response:

You can zip the input tuple of lists and iterate over the name-value pairs:

[[name, *values] for name, values in zip(*firstlst)]

CodePudding user response:

Use zip to iterate over each prefix values list, you can then use * unpacking to convert each prefix and values pair into a single list

firstlst = (["JS", "SK"], [[200, 400, 500, 600], [400, 1000, 1600]])
output = [[prefix, *values] for prefix, values in zip(*firstlst)]
print(output) # [['JS', 200, 400, 500, 600], ['SK', 400, 1000, 1600]]
  • Related