工作中遇到需要將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).