Home > other >  Novice to learn PYTHON, why this program can only be iterative loop once?
Novice to learn PYTHON, why this program can only be iterative loop once?

Time:11-01

Code:

The dataSet=[[1], [2], [3]]
D=the map (the set, the dataSet)
For I in D:
Print (I)
For I in D:
Print (I)

Results:
{1}
{2}
{3}


Why can't the second iteration?

CodePudding user response:

I am here to two
 

>
Set ([1])
Set ([2])
Set ([3])
Set ([1])
Set ([2])
Set ([3])

CodePudding user response:

I am V3.4 python version, a lot of V2 program will be adjusted, very strange

CodePudding user response:

The for loop is based on the iterator protocol

CodePudding user response:

Is in this way, the reason is that: after traversing the last element, visit will put the circular list again, we can understand like this: because the python "no pointer, but all the objects are the pointer", after completing a traversal pointer will move on to the last element, that is to say, D is a map object, print (list (D)) or a for loop to print the elements in the D, could lead to an iterator from beginning to end (which can analog the list [0] to the list [n]), and an iterator is a one-way container, after go to tail, don't automatically return to start position, therefore, was carried out on the map object after a for loop, the map is equivalent to "empty",

Want to secondary traverse Map object (access), there is a kind of method for reference:

-- -- -- -- -- - before the first traverse Map object, first a duplicate copy, but they only want to be is a deep copy of copy,
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
Author: swety_gxy
Source: CSDN
Original: https://blog.csdn.net/swety_gxy/article/details/83063499
Copyright statement: this article original articles for bloggers, reproduced please attach link to blog!
There is,

CodePudding user response:

Because the map () function returns the object is not the same as
Python 2 x returned list,
Python 3 x return iterators,
So you use 3.4 version is only one iteration
  • Related