[英]Multiply every other element in a list
我有一個列表,比方說: list = [6,2,6,2,6,2,6]
,我希望它創建一個新列表,其中每個其他元素乘以 2,每個其他元素都乘以 1(保持不變)。 結果應該是: [12,2,12,2,12,2,12]
。
def multi():
res = 0
for i in lst[0::2]:
return i * 2
print(multi)
也許是這樣,但我不知道如何繼續。 我的解決方案怎么錯了?
您可以使用切片分配和列表理解:
l = oldlist[:]
l[::2] = [x*2 for x in l[::2]]
您的解決方案是錯誤的,因為:
res
被聲明為一個數字而不是一個列表multi
這是您的代碼,已更正:
def multi(lst):
res = list(lst) # Copy the list
# Iterate through the indexes instead of the elements
for i in range(len(res)):
if i % 2 == 0:
res[i] = res[i]*2
return res
print(multi([12,2,12,2,12,2,12]))
您可以使用列表理解和enumerate
函數重建列表,如下所示
>>> [item * 2 if index % 2 == 0 else item for index, item in enumerate(lst)]
[12, 2, 12, 2, 12, 2, 12]
enumerate
函數在每次迭代中給出可迭代項和當前項的當前索引。 然后我們使用條件
item * 2 if index % 2 == 0 else item
決定要使用的實際值。 在這里, if index % 2 == 0
那么item * 2
將被使用,否則item
將按原樣使用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.