Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cant iterate nested for loop as wanted -python -maybe a simple mistake

I have tried the code below: the purpose is to generate a dictionary where each key has a list as a value. The first iteration goes well and generates the item as I want it, but the second loop, the nested for loop, doesn't generate the list as expected.

Please help me with this simple code. There must be something wrong with it, the code is as below:

 schop = [1, 3, 1, 5, 6, 2, 1, 4, 3, 5, 6, 6, 2, 2, 3, 4, 4, 5]
 mop =   [1, 1, 2, 1, 1, 1, 3, 1, 2, 2, 2, 3, 2, 3, 3, 2, 3, 3]
 mlist = ["1","2","3"]
 wmlist=zip(mop,schop)

 title ={}
 for m in mlist:
     m = int(m)
     k=[]
     for a,b in wmlist:
         if a == m:
            k.append(b)
     title[m]=k
 print(title)

The results are like:

title: {1: [1, 3, 5, 6, 2, 4], 2: [], 3: []}

Why do the second key and the third key have an empty list?

Thanks!

like image 877
Pepin Peng Avatar asked Mar 10 '18 23:03

Pepin Peng


1 Answers

Your code would have worked as you expect in Python 2, where zip creates a list of tuples.

In Python 3, zip is an iterator. Once you iterate over it, it gets exhausted, so your second and third for loops won't have anything left to iterate over.

The simplest solution here would be to create a list from the iterator:

wmlist = list(zip(mop,schop))
like image 144
Thierry Lathuille Avatar answered Nov 14 '22 21:11

Thierry Lathuille