我在串列中有元素,我想從中洗掉除某些索引值之外的所有元素,有沒有辦法?
list = ['Radar', 'completed 2022-10-23T08:18:26', 'PASS: 11FAIL: 0SKIP: 0', '0:14:55', 'completed', '2022-10-23T08:18:26']
indexes = (0, 1, -2, -1) # these are the index values i want to keep in the same list sorted in same indexes format
預期的,
list = ['Radar', 'completed 2022-10-23T08:18:26', 'completed', '2022-10-23T08:18:26']
uj5u.com熱心網友回復:
將串列替換為僅具有所需值的新串列會更容易:
xs = ['Radar', 'completed 2022-10-23T08:18:26', 'PASS: 11FAIL: 0SKIP: 0', '0:14:55', 'completed', '2022-10-23T08:18:26']
indices = (0, 1, -2, -1)
xs = [xs[i] for i in indices]
print(xs)
順便說一句,不要呼叫變數名稱,如list,這會“隱藏”list型別,使其無法訪問代碼后面的代碼并導致代碼變得混亂。
如果由于某種原因,您絕對需要一個洗掉其他索引而不是保留指定索引的解決方案:
xs = ['Radar', 'completed 2022-10-23T08:18:26', 'PASS: 11FAIL: 0SKIP: 0', '0:14:55', 'completed', '2022-10-23T08:18:26']
indices = (0, 1, -2, -1)
n = len(xs)
# turn the negative indices into positive ones
indices = tuple(n i if i < 0 else i for i in indices)
# get the indices that need to be deleted, from the end to the start
del_indices = reversed(sorted(i for i in range(n) if i not in indices))
for i in del_indices:
del xs[i]
print(xs)
這更復雜,因為當您洗掉專案時,剩余專案的索引可能會更改,除非您以正確的順序洗掉它們。只要您從末尾開始洗掉元素,一直到開頭,就不會有問題。
一個更聰明的解決方案將洗掉整個范圍,而不是一次洗掉一個元素 - 但這比它的價值更麻煩,您可能應該使用第一個解決方案。
uj5u.com熱心網友回復:
在一行中:
list = [list[i] for i in [1, 2, -1, -2]]
希望能幫助到你!
uj5u.com熱心網友回復:
我認為創建一個新串列更簡單,可能更快:
list = list[i for i in range(len(list)) if i in indices_to_keep]
也就是說,有時您需要修改作為引數傳遞的串列,或者可能具有您無法找到或更新的其他系結。您可以使用del陳述句來洗掉不需要的索引,但是每次洗掉都會更改已洗掉索引之后的所有元素的索引,因此您需要小心。一種簡單的方法是以相反的順序洗掉它們,例如:
for i in reversed(range(len(list))):
if i not in keep_indices: del list[i]
ETA:我小心翼翼地保留了未洗掉元素的原始順序。如果這不是要求,那么其他答案可能對您更有效。另外,我看到您使用的是負索引。對于那些使用上述代碼的人,您可以使用類似indices_to_keep = [x%len(list) for x in indices_to_keep].
uj5u.com熱心網友回復:
最簡單的是其他答案中建議的串列理解,但是如果您使用 pandas 庫,您可以這樣做
my_series = pd.Series(my_list)
my_series.loc[indexes]
如果您經常這樣做,或者在其他地方使用熊貓,那么熊貓開銷可能是值得的。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/522496.html
標籤:Python列表
上一篇:我是python的初學者,有人可以詳細解釋一下這段代碼嗎?
下一篇:在串列中查找短語并獲取索引
