[英]How to subtract numbers from only a few elements in a list?
我有一個包含幾個元素的列表,我只想從列表中的前 3 個元素中減去 1。 我無法弄清楚完成這項任務的正確代碼是什么。 如果有人可以幫助我,我將不勝感激。 謝謝你!
thelist = [5,4,3,2,1]
我想讓它變成
[4,3,2,2,1]
一種可能的解決方案:
thelist = [5,4,3,2,1]
thelist = [v - 1 if i < 3 else v for i, v in enumerate(thelist)]
print(thelist)
印刷:
[4, 3, 2, 2, 1]
或者:
print(list(map(lambda k: k-1, thelist[:3])) + thelist[3:])
或者:
print([v - (i<3) for i, v in enumerate(thelist)])
In [95]: thelist = [5,4,3,2,1]
In [96]: [i-1 for i in thelist[:3]] + thelist[3:]
Out[96]: [4, 3, 2, 2, 1]
您可以使用列表推導式修改原始列表,如下所示:
n = 3 # Number of first elements to modify.
modification_amount = -1
thelist[:n] = [val + modification_amount for val in thelist[:n]]
>>> thelist
[4, 3, 2, 2, 1]
>>> thelist = [5,4,3,2,1]
>>> newlist=[x-1 if thelist.index(x) < 3 else x for x in thelist]
>>> newlist
[4, 3, 2, 2, 1]
只是另一種解決方案,如果您想嘗試,可以使用 numpy
import numpy as np
thelist = [5,4,3,2,1]
newnp = np.array(thelist)
newnp[0:3] -= 1
print(list(newnp))
數組切片
首先,我們需要將數組拆分為 2 個組件,前 3 個元素: first_three =x[:3]
和剩余的remainder = x[3:]
列表理解
我們現在可以從first_three
每個項目中減去 1,並將結果保存在一個新數組中one_subtracted = [num - 1 for num in first_three]
最終的
然后我們可以通過將數組加在一起來創建結果result = one_subtracted + remainder
速記
您也可以將其作為單個表達式的一部分執行
the_list = [5,4,3,2,1]
result = [num - 1 for num in the_list[:3]] + the_list[3:]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.