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

How to create a zip of zip of a list in python. I need it for a double for loop

I have the following lists:

mylist1 = ["peru", "germany", "japan"]
mylist2 = [["lima","cusco"], ["berlin","munich"], ["tokyo"]]
mylist3=[[1,2],[3,4],[5]]

and I want to print

peru
lima
1
cusco
2

germany
berlin
3
munich
4

japan
tokyo
5

One zip command looks like:

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

list=list(zip(mylist1,mylist2,mylist3))

for country,cities,nums in list:
    print(country)
    for city in cities:
         print(city)
    for num in nums:
         print(num)

But as you can guess, it won’t output what I want. So I thought of a double zip like
list = list(zip(mylist1,zip(mylist2,mylist3))), and then

for country,info in list:
    print(country)
    for city,num in info:
         print(city)
         print(num)

But it doesn’t work. I do need 2 for loops. One for the country and a second one to handle the other info.

>Solution :

You can do it like this using three zips in total, although you can do it in a simpler way if you use indices with enumerate (assuming the lists have the same length):

mylist1 = ["peru", "germany", "japan"]
mylist2 = [["lima","cusco"], ["berlin","munich"], ["tokyo"]]
mylist3 = [[1,2], [3,4], [5]]

for country, (cities, numbers) in zip(mylist1, zip(mylist2, mylist3)):
    print(country)
    for city, number in zip(cities, numbers):
        print(city)
        print(number)
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