【问题标题】:make a total list of a returned map (python)制作返回地图的总列表(python)
【发布时间】:2013-11-13 16:56:06
【问题描述】:

我有 lambda 函数 f:

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

我有列表 lst:

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

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

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

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

我该怎么做?

【问题讨论】:

    标签: python map lambda return


    【解决方案1】:

    使用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']
    

    【讨论】:

      【解决方案2】:

      试试:

      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]
      

      【讨论】:

        【解决方案3】:

        您可以使用列表推导来展平这些列表。

        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']
        

        【讨论】:

          【解决方案4】:
          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']

          【讨论】:

            猜你喜欢
            • 2016-10-03
            • 2012-11-26
            • 2016-09-23
            • 2016-02-17
            • 1970-01-01
            • 1970-01-01
            • 2012-05-30
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多