我有一個列表,讓我們說: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)
也許這樣的事情,但我不知道如何繼續前進。我的解決方案錯了?
我有一個列表,讓我們說: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]))
可以重建有列表comprehenstion和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
原樣。