2013-11-02 36 views
0

我有拉姆達函數f:使返回的映射(蟒蛇)的總名單

f = lambda x:["a"+x, x+"a"] 

和我有列表LST:

lst = ["hello", "world", "!"] 

所以我做了地圖上的功能和列表以獲得更大的名單,但沒有工作,我想:

print map(f, lst) 
>>[ ["ahello", "helloa"], ["aworld", "worlda"], ["a!", "!a"] ] 

正如你可以看到我走進去列表清單,但我想所有這些字符串是在one list

我該怎麼做?

回答

1
f1 = lambda x: "a" + x 
f2 = lambda x: x + "a" 
l2 = map(f1,lst) + map(f2,lst) 
print l2 

[ 'ahello', 'aworld', '一個!', 'helloa', 'worlda', '!一個']

2

使用itertools.chain.from_iterable

>>> import itertools 
>>> f = lambda x: ["a"+x, x+"a"] 
>>> lst = ["hello", "world", "!"] 
>>> list(itertools.chain.from_iterable(map(f, lst))) 
['ahello', 'helloa', 'aworld', 'worlda', 'a!', '!a'] 

替代(列表理解):

>>> [x for xs in map(f, lst) for x in xs] 
['ahello', 'helloa', 'aworld', 'worlda', 'a!', '!a'] 
0

嘗試:

from itertools import chain 

f = lambda x:["a"+x, x+"a"] 
lst = ["hello", "world", "!"] 

print list(chain.from_iterable(map(f, lst))) 

>> ['ahello', 'helloa', 'aworld', 'worlda', 'a!', '!a'] 

對於文檔看答案來自falsetru。

不錯的選擇是使用扁平化功能:

from compiler.ast import flatten 

f = lambda x:["a"+x, x+"a"] 
lst = ["hello", "world", "!"] 

print flatten(map(f, lst)) 

扁平化功能的好處:它可以拼合不規則的名單:

print flatten([1, [2, [3, [4, 5]]]]) 
>> [1, 2, 3, 4, 5] 
0

您可以使用列表解析來拉平這些列表。

f = lambda x:["a"+x, x+"a"] 
lst = ["hello", "world", "!"] 
print [item for items in map(f, lst) for item in items] 

輸出

['ahello', 'helloa', 'aworld', 'worlda', 'a!', '!a']