Home > database >  Python - Concatenating and printing the elements of a 3D list
Python - Concatenating and printing the elements of a 3D list

Time:08-24

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?

CodePudding user response:

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

CodePudding user response:

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)   "\n"

print(lali)
  • Related