【问题标题】:Concatenate elements in two lists with different length连接两个不同长度列表中的元素
【发布时间】:2018-06-27 10:28:50
【问题描述】:

(我确定这已经在某个地方得到了回答,但我真的找不到正确的问题。也许我不知道这个练习的正确动词?)

我有两个列表:

prefix = ['A', 'B', 'C']
suffix = ['a', 'b']

我想得到这个:

output = ['A a', 'A b', 'B a', 'B b', 'C a', 'C b']

我知道zip 方法,它在加入的列表中的最短长度处停止:

output_wrong = [p+' '+s for p,s in zip(prefix,suffix)]

那么,最 Pythonic 的方式是什么?

编辑:

虽然大多数答案更喜欢itertools.product,但我更喜欢这个:

output = [i + ' ' + j for i in prefix for j in suffix]

因为它没有引入新的包,但该包是基本的(好吧,我不知道哪种方式更快,这可能是个人喜好问题)。

【问题讨论】:

  • 我喜欢我们在一分钟内得到大致相同问题的 4 个答案。 :D
  • @MateenUlhaq 那里有数百个类似的问题,我们不应该回答这个问题,而应该将 OP 指向其中之一,但你知道的。
  • @BcK 公平地说,我已经达到了当天的代表上限,只想写一个itertools 答案。 ;) ...虽然作为重复关闭可能是更准确的做法。
  • 正如我所说,我可能不知道正确的词,在这种情况下是“笛卡尔积”。谢谢你们指出这一点。

标签: python list concatenation


【解决方案1】:

使用列表理解

prefix = ['A', 'B', 'C']
suffix = ['a', 'b']
result = [val+" "+val2 for val in prefix for val2 in suffix ]
print(result)

输出

['A a', 'A b', 'B a', 'B b', 'C a', 'C b']

【讨论】:

    【解决方案2】:

    使用itertools.product 和列表理解,

    >>> [i + ' ' + j for i, j in product(prefix, suffix)]
    # ['A a', 'A b', 'B a', 'B b', 'C a', 'C b']
    

    【讨论】:

      【解决方案3】:

      使用itertools.product:

      import itertools
      
      prefix = ['A', 'B', 'C']
      suffix = ['a', 'b']
      
      print([f'{x} {y}' for x, y in itertools.product(prefix, suffix)])
      # ['A a', 'A b', 'B a', 'B b', 'C a', 'C b']
      

      【讨论】:

        【解决方案4】:

        这称为笛卡尔积:

        [p + ' ' + s for p, s in itertools.product(prefix, suffix)]
        

        【讨论】:

          【解决方案5】:

          使用product

          In [33]: from itertools import product
          
          In [34]: map(lambda x:' '.join(x),product(prefix,suffix))
          Out[34]: ['A a', 'A b', 'B a', 'B b', 'C a', 'C b']
          

          【讨论】:

          • 您转换为列表是否有原因?
          【解决方案6】:

          只需使用list comprehension:

          prefix = ['A', 'B', 'C']
          suffix = ['a', 'b']
          output = [i+" "+j for i in prefix for j in suffix]
          print(output)
          

          输出:

          ['A a', 'A b', 'B a', 'B b', 'C a', 'C b']
          

          【讨论】:

            【解决方案7】:
            from itertools import product
            map(' '.join, product(prefix, suffix))
            # ['A a', 'A b', 'B a', 'B b', 'C a', 'C b']
            

            【讨论】:

              猜你喜欢
              • 2017-08-30
              • 1970-01-01
              • 2019-11-30
              • 1970-01-01
              • 1970-01-01
              • 2013-08-02
              • 1970-01-01
              • 1970-01-01
              • 2023-01-13
              相关资源
              最近更新 更多