工做中遇到須要將List對象中的元素(list類型)轉化爲集合(set)類型,轉化完成以後須要須要訪問其中的元素。html
第一步,使用map方法進行轉換python
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>
第二步,訪問mapide
從第一步打印data能夠看到map對象返回的是一個地址,不是真實的數據。 (map() and filter() return iterators.)oop
關於迭代器咱們作一個實驗,會發現遍歷完最後一個元素後,再次訪問時會放回空列表。ui
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以後存在另一個變量中。有兩種方式,以下:spa
第一種方式 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-listscode
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).orm