2014-09-12 83 views
2

是否有一種簡單的方法將雙列表轉換爲雙列表列表?Python列表到列表

例如:

[1.0, 2.0, 3.0] 

[[1.0], [2.0], [3.0]] 

我正在使用的代碼需要第二作爲輸入一堆的功能,但是這很煩人有相同的數據的兩個副本。

回答

18

只需使用一個list-comprehension包裹每個元素的列表:

l = [1.0, 2.0, 3.0] 
print [[x] for x in l] 
[[1.0], [2.0], [3.0]] 
2

作爲替代列出解析,你可以嘗試map

>>> map(lambda x: [x], l) 
[[1.0], [2.0], [3.0]] 

這使得通過應用lambda期望的結果函數(在這裏,將一個對象放在一個列表中)依次到每個元素l

在Python 3中map返回一個迭代器,所以使用list(map(lambda x: [x], l))來獲取列表。


使用map兩倍左右列表修真0​​小列爲慢,因爲建設lambda功能會帶來小的開銷:

>>> %timeit [[x] for x in l] 
1000000 loops, best of 3: 594 ns per loop 

>>> %timeit map(lambda x: [x], l) 
1000000 loops, best of 3: 1.25 us per loop 

對於更長的名單中,兩次啓動之間的時間間隔關閉,儘管列表理解仍然是preferred option in the Python community

+0

*有趣*?這似乎很明顯,爲什麼..請參考http://stackoverflow.com/questions/1247486/python-list-comprehension-vs-map順便說一句,我喜歡'地圖'更多;) – 2015-05-04 11:39:22

+0

感謝您指出這一點 - d打算把這個詞*有趣地*表示爲「值得注意」而不是「神祕地」......我會用一個更好的詞來更新我的答案,並解釋爲什麼:-) – 2015-05-04 11:54:50

+0

如果你找到一種方法不要在這裏使用'lambda',那麼'map'會更快! – 2015-05-04 11:55:56

0

它可能不是必要的,但如果列表內涵是神祕的,這裏是一個使用for循環的通用解決方案:

def convert(l): 
    converted = [] 
    if isinstance(l, list): 
     if len(l) > 0: 
      for n in l: 
       converted.append([n]) 
    return converted 

l = [1.0, 2.0, 3.0] 
print convert(l) 

你也可以請檢查是否列表中的每個元素是浮動或不,並提高一個錯誤,如果其中一人是不是:

class NotFloatError(Exception): 

    def __init__(self, message): 
     Exception.__init__(self, message) 

def convert(l): 
    converted = [] 
    if isinstance(l, list): 
     if len(l) > 0: 
      for n in l: 
       if isinstance(n, float): 
        converted.append([n]) 
       else: 
        raise NotFloatError("An element in the list is not a float.") 
    return converted 

l = [1.0, 2.0, 3.0] 
print convert(l) 
+2

我認爲這比列表理解更加神祕。 – Derek 2015-01-14 15:47:57

0
a = [1.0, 2.0, 3.0] 
for x in a: 
    a = [x] 
    print a