Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading