zoukankan      html  css  js  c++  java
  • 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).

  • 相关阅读:
    memcached与.NET的融合使用(二)
    memcached与.NET的融合使用(一)
    使用window2003安装邮件服务器最新实际操作记录
    2014 -> 2015
    数据挖掘入门 资料和步骤
    CSDN 论坛招聘区是不是有潜规则?在Cnblog招个人试试...
    C#薪水和前途
    面试准备
    面试准备
    面试准备
  • 原文地址:https://www.cnblogs.com/lyy-totoro/p/7018597.html
Copyright © 2011-2022 走看看