0

我有 lambda 函数 f:

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

我有清单:

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

所以我确实映射了函数和列表以获得更大的列表,但它并没有像我想的那样工作:

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

如您所见,我在列表中找到了列表,但我希望所有这些字符串都在一个列表中

我怎样才能做到这一点?

4

4 回答 4

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']
于 2013-11-02T17:18:19.923 回答
1
f1 = lambda x: "a" + x
f2 = lambda x: x + "a"
l2 = map(f1,lst) + map(f2,lst)
print l2

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

于 2013-11-02T17:21:13.503 回答
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 的答案。

不错的选择是使用 flatten 功能:

from compiler.ast import flatten

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

print flatten(map(f, lst))

flatten 函数的好处:它可以使不规则列表变平:

print flatten([1, [2, [3, [4, 5]]]])
>> [1, 2, 3, 4, 5]
于 2013-11-02T17:18:36.233 回答
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']
于 2013-11-02T17:19:58.350 回答