簡體   English   中英

如何以較短的列表重復的方式將兩個不同長度的列表相乘?

[英]How can I multiply two lists of different lengths in such a way that the shorter list repeats?

我需要將這兩個列表相乘,但一個很長,另一個很短,長列表的長度是短列表長度的倍數。 如何以重復短的方式將它們相乘,直到長列表中的所有元素都乘以它。

例如:

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

我正在嘗試做的事情:

longList * shortList # Something like this

所需 output

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

*這不是如何 zip 兩個不同大小的列表的副本? 因為我不是在尋找 zip 它們,而是將它們相乘。

您可以通過一個簡單的循環和 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)

解決方案

即使 longList 中的元素數量不是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)]

Output

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

以下 pythonic function (使用列表理解)應該可以工作:

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]

希望有幫助:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM