它顯示串列索引超出范圍。我需要洗掉所有奇數索引元素,但它不作業,顯示串列索引超出范圍
。list1 = [12, 33,45,66, 75, 33,4,56。 66,67,1, 2]
for i in range(len(list1))。
x=i
if(i%2! =0)。
#print(list1[x]).
list1.remove(list1[x])
else:
繼續: 繼續?
print(list1)
uj5u.com熱心網友回復:
只要這樣做,它應該可以作業
list1 = [12, 33,45,66, 75, 33,4,56。 66,67,1, 2]
list1=list1[::2]
print(list1)`。
輸出:-
[12, 45, 75, 4, 66, 1]/code>
uj5u.com熱心網友回復:
問題:
。你的代碼對給定的片段不起作用,因為每當你從list1中洗掉一個元素時,同一元素的一個索引就會被消除。
解決方案:
為了使用迭代法克服這個問題,你需要將偶數元素追加到另一個串列中,或者如Pratyush Arora所說,任何都可以。如果你使用的是迭代法,這可能會有幫助:
如果你使用的是迭代法,這可能會有幫助。
代碼:
list1 = [12, 33,45,66, 75, 33,4,56。 66,67,1, 2]
# 使用串列理解法
evenIndexList = [i for indexValue, i in enumerate(list1) if indexValue % 2 == 0 ]
print(evenIndexList)
# Standard approach
newList = []
for i in range(len(list1))。
if i % 2 == 0:
newList.append(list1[i])
print(newList)
uj5u.com熱心網友回復:
解決方案
del list1[1::2]
這是從"移除所有奇數索引元素"直接翻譯成Python代碼的。
Benchmark以及一個有一百萬個元素的串列的upvoted solution:
11.8 ms 11.9 ms 12.0 ms list1 = list1[:: 2]
90.1 ms 90.6 ms 91. 1 ms list1 = [i for indexValue, i in enumerate(list1) if indexValue % 2 == 0 ]
8.0 ms 8.2 ms 8。 2 ms del list1[1::2]
Benchmark代碼(Try it online!):
from timeit import repeat
setup = 'list1 = list(range(10**6))'/span>
解決方案 = [
'list1=list1[::2]'。
'list1 = [i for indexValue, i in enumerate(list1) if indexValue % 2 == 0]',
'del list1[1::2]'。
]
for _ in range(3)。
for solution in solutions:
times = sorted(repeat(solution, setup, number=1)) [:3]
print(*('%4.1f ms ' % (t * 1e3) fort in times), solution)
print()
uj5u.com熱心網友回復:
執行以下操作:
list1 = [12, 33,45,66, 75, 33,4,56。 66,67,1, 2]
list1 = [list1[i] for i in range(0, len(list1),2) ]
print(list1)
輸出 :
[12, 45, 75, 4, 66, 1]
uj5u.com熱心網友回復:
如果你想用你的方式,你可以使用它:
list1 = [12, 33,45,66, 75, 33,4,56。 66,67,1, 2]
list2 = []
for i in range(len(list1))。
if(i%2! =1)。
list2.append(list1[i])
print(list2)
list2包含所有的偶數
uj5u.com熱心網友回復:你可以使用del
list1 = [12, 33,45,66, 75, 33,4,56。 66,67,1, 2]
del list1[1::2] # any_list[start: end: steps] Here, end = None
print(list1)
索引[1::2]
----------------------------------------------------------
專案 | 12 | 33 | 45 | 66 | 75 | 33 | 4 | 56 | 66 ? 數字">66 | 67 | 1 | 2 !
索引 | 0 | 1 | 2 | 3 | 4 5 | 6 | 7 | 8 ! 數字">8 | 9 | 10 | 11 !
1::2 | | | | | | | | | |
----------------------------------------------------------
因此,所有打勾的標記將從你的串列中洗掉。
對于學習python參考.
uj5u.com熱心網友回復:
from copy import deepcopy
list1 = [12,33,45,66,75, 33, 4,56,66,67, 1,2]
list2 = deepcopy(list1)
for i in range(len(list2))。
if(i%2! =0)。
#print(list1[x]).
list1.remove(list2[i])
else:
繼續: 繼續?
print(list1)
當我們試圖從一個串列中洗掉一個元素,同時又在同一個串列中迭代時,就會出現上述問題。
為了克服這個問題,我們可以使用 deepcopy 創建一個串列的副本,然后迭代 list2。對于洗掉的元素使用list1。
輸出
[12, 45, 75, 4, 66, 1]
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/332546.html
標籤:
下一篇:用隨機值對創建串列
