Python – Concatenating and printing the elements of a 3D list

Question:

I am trying to combine the elements of a 3D string list into a single string.

eleli = [[["ele1"]], [["ele2"]], [["ele3"]], [["ele4"]], [["ele5"]]]

elecom = [i for i in eleli for i in i for i in i]

lali = ""
for a in elecom:
    lali += a + "n"

print(lali)

>>>ele1
ele2
ele3
ele4
ele5

The above operation will give you the desired result. But the code is too stupid. Can you make it simpler?

Asked By: anfwkdrn

||

Answers:

We can actually use a single list comprehension here along with join():

eleli = [[["ele1"]], [["ele2"]], [["ele3"]], [["ele4"]], [["ele5"]]]
output = "".join([x[0][0] for x in eleli])
print(output)  # ele1ele2ele3ele4ele5

To address the input suggested by @anto, we can try:

eleli = [[["ele1"]], [["ele2","other_ele2"]], [["ele3"]], [["ele4"]], [["ele5"]]]
output = "".join(["".join(x[0]) for x in eleli])
print(output)  # ele1ele2other_ele2ele3ele4ele5
Answered By: Tim Biegeleisen

If your main concern is readibility, I think this is more readable than the version you provided:

eleli = [[["ele1"]], [["ele2"]], [["ele3"]], [["ele4"]], [["ele5"]]]

eleli_2d = [item for sublist in eleli for item in sublist]

eleli_1d = [item for sublist in eleli_2d for item in sublist]

lali = "n".join(eleli_1d)
lali += "n"

print(lali)
Answered By: Kike Laguilhoat
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.