python3.x 中map对象的访问方式


工作中遇到需要将List对象中的元素(list类型)转化为集合(set)类型,转化完成之后需要需要访问其中的元素。

第一步,使用map方法进行转换

data = [[1, 3, 4], [2, 3, 5], [1, 2, 3, 5], [2, 5]] print(data) [[1, 3, 4], [2, 3, 5], [1, 2, 3, 5], [2, 5]]
-------------------------
data = map(set,data) 
print(data)

<map object at 0x000002EF0C5202E8>

第二步,访问map

从第一步打印data可以看到map对象返回的是一个地址,不是真实的数据。  (map() and filter() return iterators.)

关于迭代器我们做一个实验,会发现遍历完最后一个元素后,再次访问时会放回空列表。

print(list(data)) [{1, 3, 4}, {2, 3, 5}, {1, 2, 3, 5}, {2, 5}] -----------------  第一次变量可以正常返回需要的结果

print(list(data)) [] ----------------- 第二次遍历则为空了,因为上一次已经走到尾部了

print(len(list(data)) 0

为了能持续正确的访问数据,需要将其list comprehension之后存在另外一个变量中。有两种方式,如下:

 

第一种方式 list1 = list(data) print(list1) [{1, 3, 4}, {2, 3, 5}, {1, 2, 3, 5}, {2, 5}] ------------------------------------------- 或者第二种方式 list1 = [item for item in data] print(list1) [{1, 3, 4}, {2, 3, 5}, {1, 2, 3, 5}, {2, 5}]

 

关于map有一个参考的连接:https://docs.python.org/3/whatsnew/3.0.html#views-and-iterators-instead-of-lists

map() and filter() return iterators. If you really need a list and the input sequences are all of equal length, a quick fix is to wrap map() in list(), e.g. list(map(...)), but a better fix is often to use a list comprehension (especially when the original code uses lambda), or rewriting the code so it doesn’t need a list at all. Particularly tricky is map() invoked for the side effects of the function; the correct transformation is to use a regular for loop (since creating a list would just be wasteful).


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM