Issue
In the following code, first create a list collection in the loadDataSet () function, and then use the map function to convert it into a set D ,after that,it can only print once and become enpty.Does anyone know what is going on here? thank you.
def loadDataSet():
return [ [ 1, 3, 4 ], [ 2, 3, 5 ], [ 1, 2, 3, 5 ], [ 2, 5 ] ]
if __name__ == '__main__':
myDat = loadDataSet()
D = map( set, myDat )
print("first print: ",list(D))
print("second print: ",list(D))
print("len of D: ",len(list(D)))
i use python 3.5.2 and the output is :
first print: [{1, 3, 4}, {2, 3, 5}, {1, 2, 3, 5}, {2, 5}]
second print: []
len of D: 0
Solution
The reason is because of the behavior of map()
function itself. It returns a generator, which can only be consumed once. This means, map can only execute the function to the list of given inputs once and return the resulting object. After that, the generator is exhausted and cannot be used to generate the same result. Therefore, the practice is to save the return value in a variable if you are going to use it more than once.
Answered By - Andreas
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.