Home > Blockchain >  Two lists: Combine on values of the other list
Two lists: Combine on values of the other list

Time:10-05

I have the follow two lists:

1: ['GL50IILW', 'GL50IILW', 'NLR1R1RXCH', 'NNH0NNB7', 'QB2XP6MCH', 'QB2XP6MCH', 'KLEESZA1CH', 'KLEESZA1CH', 'UL50IALW', 'UL50IALW', 'UL50IALW', 'BHFFZA', 'BHFFZA', 'BHFFZA']
2: [2, 2, 2, 2, 3, 3]

I would like to combine the first list with the second for an output of:

['GL50IILW,GL50IILW','NLR1R1RXCH,NLR1R1RXCH','QB2XP6MCH,QB2XP6MCH','KLEESZA1CH,KLEESZA1CH','UL50IALW,UL50IALW,UL50IALW','BHFFZA,BHFFZA,BHFFZA']

List 1's values gets combined on Lists 2 index value.

CodePudding user response:

Try:

l1 = [
    "GL50IILW",
    "GL50IILW",
    "NLR1R1RXCH",
    "NNH0NNB7",
    "QB2XP6MCH",
    "QB2XP6MCH",
    "KLEESZA1CH",
    "KLEESZA1CH",
    "UL50IALW",
    "UL50IALW",
    "UL50IALW",
    "BHFFZA",
    "BHFFZA",
    "BHFFZA",
]
l2 = [2, 2, 2, 2, 3, 3]

i = iter(l1)
out = [",".join(next(i) for _ in range(v)) for v in l2]

print(out)

Prints:

[
    "GL50IILW,GL50IILW",
    "NNH0NNB7,NLR1R1RXCH",
    "QB2XP6MCH,QB2XP6MCH",
    "KLEESZA1CH,KLEESZA1CH",
    "UL50IALW,UL50IALW,UL50IALW",
    "BHFFZA,BHFFZA,BHFFZA",
]
  • Related