【问题标题】:How can I multiply two lists of different lengths in such a way that the shorter list repeats?如何以较短的列表重复的方式将两个不同长度的列表相乘?
【发布时间】:2019-10-17 00:06:33
【问题描述】:

我需要将这两个列表相乘,但一个很长,另一个很短,长列表的长度是短列表长度的倍数。我怎样才能以一种重复短的方式将它们相乘,直到长列表中的所有元素都乘以它。

例如:

longList = [10, 10, 10, 10, 10, 10, 10, 10, 10] 
shortList = [1, 2, 3]

我想做什么:

longList * shortList # Something like this

期望的输出

[10, 20, 30, 10, 20, 30, 10, 20, 30] 

*这不是How to zip two differently sized lists? 的复制品,因为我不想压缩它们,而是将它们相乘。

【问题讨论】:

  • 我可能应该在longList 中使用整数,实际上我确实想将两个列表相乘而不是压缩它们。 @uneven_mark
  • 压缩只是准备工作。然后您必须在列表理解中使用它:[a*b for a,b in zip_list]。我以为这不是你要问的。
  • 您的问题是关于压缩两个不同长度的列表吗?
  • @DanielMesejo 我不认为它是,但不均匀_mark 上面的评论回答了我的问题

标签: python list


【解决方案1】:

你可以通过一个简单的循环和 itertools 来实现这一点

import itertools

longList = [1, 0, 2, 6, 3, 4, 5, 3, 1]
shortList = [1, 2, 3]

output_list = []

for long, short in zip(longList, itertools.cycle(shortList)):
    output_list.append(long * short)

【讨论】:

    【解决方案2】:

    解决方案

    即使longList 中的元素数量不是shortList 的精确倍数,以下代码也将起作用。它也不需要任何import 语句。

    longList = [10, 10, 10, 10, 10, 10, 10, 10, 10,] 
    shortList = [1, 2, 3]
    
    container = list()
    n = len(longList)%len(shortList)
    m = int(len(longList)/len(shortList))
    for _ in range(m):
        container += shortList.copy()     
    if n>0:
        container += shortList[:n]
    [e*f for e,f in zip(container, longList)]
    

    输出

    [10, 20, 30, 10, 20, 30, 10, 20, 30]
    

    【讨论】:

      【解决方案3】:

      以下pythonic函数(使用list comprehension)应该可以工作:

      def loop_multiply(ll,sl) : 
          return [ x*sl[i%len(sl)] for i,x in enumerate(ll) ] 
      
      
      print(loop_multiply([10,10,10,10,10,10,10,10,10],[1,2,3])) 
      # prints - [10, 20, 30, 10, 20, 30, 10, 20, 30]
      

      希望有帮助:)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-01-26
        • 1970-01-01
        • 1970-01-01
        • 2021-02-25
        • 2017-12-24
        • 2021-03-18
        • 2015-11-05
        • 2017-07-23
        相关资源
        最近更新 更多