【问题标题】:Python How to pair two list by lambda and mapPython如何通过lambda和map配对两个列表
【发布时间】:2017-06-29 16:59:57
【问题描述】:

例如,我有以下两个列表

listA=['一','二','三'] listB=['苹果','樱桃','西瓜']

如何使用maplambda 将这两个列表配对以获得此输出?

one apple
two cherry
three watermelon

我知道如何通过列表理解来做到这一点,

[print(listA[i], listB[i]) for i in range(len(listA))]

但我想不出maplambda 的解决方案。有什么想法吗?

【问题讨论】:

  • 为什么不zip()
  • 这是zip()的标准用例。
  • print(..)?为什么print?此外,这看起来像是家庭作业。
  • 你不能在你的情况下使用列表理解。
  • 不要在列表理解中使用print。那是非常糟糕的风格,因为它在函数构造中使用了副作用。

标签: python lambda


【解决方案1】:

这是我根据您的需要(地图和 lambda)得到的,

输入:

listA=['one', 'two' , 'three']
listB=['apple','cherry','watermelon']
list(map(lambda x, y: x+ ' ' +y, listA, listB))

输出:

['one apple', 'two cherry', 'three watermelon']

【讨论】:

    【解决方案2】:

    最简单的解决方案是简单地使用zip,如下所示:

    >>> listA=['one', 'two' , 'three']
    >>> listB=['apple','cherry','watermelon']
    >>> list(zip(listA, listB))
    [('one', 'apple'), ('two', 'cherry'), ('three', 'watermelon')]
    

    我想可以使用 map 和 lambdas,但这只会使事情变得不必要地复杂化,因为这确实是 zip 的理想情况。

    【讨论】:

      【解决方案3】:

      使用列表理解和 zip:

      listA=['one', 'two' , 'three']
      
      listB=['apple','cherry','watermelon']
      
      new_list = [a+" "+b for a, b in zip(listA, listB)]
      

      输出:

      ['one apple', 'two cherry', 'three watermelon']
      

      【讨论】:

        【解决方案4】:

        假设有两个列表,例如 list1,list2。我们可以在列表或元组类型中对它们进行配对。

        list1=['1', '2' , '3']
        list2=['3','2','1']
        output = list (map (  lambda x,y: [x,y], list1,list2    ))
        print(output)
        

        输出:

        [['1', '3'], ['2', '2'], ['3', '1']]
        

        【讨论】:

          【解决方案5】:

          您可以使用zip,如下所示:

          for item in zip(list_1, list_2):
              print(item)
          

          【讨论】:

            【解决方案6】:

            特别是按照要求使用 map 和 lambda...

            list(map(lambda tup: ' '.join(list(tup)), zip(listA,listB)))
            

            虽然我可能会将其分解以使其更具可读性

            zipped   = zip(listA,listB)
            tup2str  = lambda tup: ' '.join(list(tup))
            result   = list(map(tup2str, zipped))
            # ['one apple', 'two cherry', 'three watermelon']
            

            已编辑 - 根据下面的评论,listCombined = list(zip(listA,listB)) 是一种浪费

            【讨论】:

            • 不要使用list(zip(listA,listB)))... 你为什么要从你的 zip 迭代器中列出一个列表?这违背了整个目的。
            猜你喜欢
            • 1970-01-01
            • 2021-02-25
            • 2018-08-27
            • 1970-01-01
            • 1970-01-01
            • 2020-06-26
            • 2013-04-30
            • 1970-01-01
            • 2021-02-09
            相关资源
            最近更新 更多