2012-08-14 238 views
0

可能重複:
Flatten (an irregular) list of lists in Python獲取列表名單列表的單一元素

我有一個像

l=[1,2,[3,4,5],[[4,2,4],[4,7,8]]] 

我想用一組在Python列表獲取所有的唯一值,但這不成功

set(l) 

TypeError: unhashable type: 'list' 

那麼有人幫忙嗎?想要使用列表等列表的設置THX

+3

你需要的是[扁平化列表](http://stackoverflow.com/questions/2158395/flatten-an-irregular-list-of-lists-in-python) – StoryTeller 2012-08-14 14:12:30

+0

爲什麼你有不均勻的嵌套數據? – Julian 2012-08-14 14:15:10

+0

非常感謝!該代碼適用於使用set! Thx – user1598203 2012-08-14 14:17:06

回答

4

你需要'放鬆',或扁平化嵌套結構,然後纔可以將它放在一個集合中。您可以使用一個發電機,爲了保持這種高效的大型列表:

def flatten(lst): 
    for element in lst: 
     if isinstance(element, list): 
      for subelement in flatten(element): 
       yield subelement 
     else: 
      yield element 

然後用它生成列表l上創建一組:

set(flatten(l)) 
+0

是的,這很有用,非常感謝你! – user1598203 2012-08-14 14:18:38

1

如何對這種做法,你拼合首先列出,然後再對其應用設置操作。

import collections 

def flat_list(tlist): 
    if isinstance(tlist, collections.Iterable): 
     return [j for i in tlist for j in flat_list(i)] 
    else: 
     return [tlist] 

則:

myl=[1,2,[3,4,5],[[4,2,4],[4,7,8]]] 

print set(flat_list(myl)) 

給出:

set([1, 2, 3, 4, 5, 7, 8]) 

與發電機@MartijnPieters方法將具有非常大的名單更有效地工作比這list comprehension基礎的方法。