如何将两个不同长度的列表相乘,使较短的列表重复?

2024-07-05 15:24:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要将这两个列表相乘,但一个很长,另一个很短,长列表的长度是短列表长度的倍数。我怎样才能将它们相乘,直到长列表中的所有元素都被相乘为止。你知道吗

例如:

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?的副本,因为我不希望压缩它们,而是希望将它们相乘。你知道吗


Tags: to元素列表zipthissomethinglistslike
3条回答

解决方案

即使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]

您可以通过一个简单的循环和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)

以下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]

希望有帮助:)

相关问题 更多 >