Home > Mobile >  Is there a better way to join elements from three lists than a triple nested for loop?
Is there a better way to join elements from three lists than a triple nested for loop?

Time:09-30

I have three lists like so:

l1 = ['a', 'b', 'c']
l2 = ['d', 'e', 'f']
l3 = ['h', 'i', 'j']

Now, what I am trying to do is combine all the elements that are in the same position on one line like so:

line_1: 'adh'
line_2: 'bei'
line_3: 'cfj'

is there a better way to do this than a triple nested for loop?

for i in range(len(l1)):
    for j in range(len(l2)):
        for k in range(len(l3)):
            if i == j and j == k:
                print(l1[i]   l2[j]   l3[k])

Basically I am trying to get something running faster than O(n^3) because I have about 100,000 items I would like to do this with.

Not sure if there would be a way with the CSV module to do this but after the combining each row is going to be written to a csv file. I have not found what I am looking for thus far and figured someone out in the community might know how to better approach this.

Wow thanks everyone who took a look at this!. There were a couple answers and they all worked. I am going to mark the question answered for whoever posted first. Thanks again to everyone who took a look! I did not even know about the zip function.

CodePudding user response:

You probably want something like:

l1 = ['a', 'b', 'c']
l2 = ['d', 'e', 'f']
l3 = ['h', 'i', 'j']

for line in (''.join(t) for t in zip(l1, l2, l3)):
    print(line)

CodePudding user response:

How about this?

l1 = ['a', 'b', 'c']
l2 = ['d', 'e', 'f']
l3 = ['h', 'i', 'j']
for a,b,c in zip(l1, l2, l3):
   print(a, b, c)

But even the pattern you went with works fine if you cut the redundant recursion:

for i in range(len(l1)):
   print(l1[i], l2[i], l3[i])

Edit: as noted in the other answer, you have to join them up again afterwards ;)

CodePudding user response:

You can use only one loop, assuming that all lists have the same length:

for i in range(len(l1)):
    print(l1[i] l2[i] l3[i])

CodePudding user response:

In one line, simplified by @juanpa.arrivillaga:

>>> list(map(''.join, zip(l1, l2, l3)))
['adh', 'bei', 'cfj']

OR, suggested by @2e0byo with a comprehension:

>>> ["".join(x) for x in zip(l1, l2, l3)]
['adh', 'bei', 'cfj']
  • Related