Can not iterate inested for loop however you want -python-maybe a simple mistake

I tried the code below: the goal is to generate a dictionary where each key has a list as a value. The first iteration goes well and generates the element as I want, but the second loop, the nested loop, does not generate the list as expected.

Please help me with this simple code. There should be something wrong with it, the code looks like this:

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 as follows:

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

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

Thanks!

+5
source share
2 answers

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

In Python 3, zip is an iterator. Once you iterate over it, it is exhausted, so your second and third for loops will not have anything that could be iterated over.

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

 wmlist = list(zip(mop,schop)) 
+7
source

I think the best thing you need to consider is the version of python you installed. This is the result I got with your code in python2: enter image description here

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

But with Python3, this is the answer I got:

enter image description here

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

If you are sure that you have the correct vesion, you only need to consider the indentation that you have in the code. Good luck

-1
source

Source: https://habr.com/ru/post/1275826/


All Articles