[英]Is it possible to ignore the last element of a list without having to create another list and without modifing the original list?
我需要在使用for
忽略列表的最后一個元素,而無需在流程上創建任何其他列表或修改主列表。
並且,如果在其他任何位置(不是最后一個位置)重復了最后一個元素,也不會忽略最后一個元素。 因此,僅忽略其位置。
在這里我忽略了它,但是我不得不創建1個額外的列表:
list1 = [3,2,3] list1_without_last = list1
list1_without_last.remove(list1_without_last[len(list1_without_last)-1])
for i in list1_without_last :
#do something
我需要這樣的東西:
list1 = [3,2,3] for i in list1 except_list1_last_element:
Ex1: list3 = [4,5,4,5]輸出:[4,5,4]
Ex2: list4 = [1,2,3,4]輸出:[1,2,3]
規范的方法是使用range
通過索引訪問項目。 比較索引和列表的長度是檢查它是否為最后一個元素的最簡單方法。
for i in range(len(some_list) - 1):
item = some_list[i]
不支持len
或索引的迭代器的另一種方法是使用itertools.tee
保留迭代器的前瞻性副本,並在前瞻性結束時停止原始運算符的迭代。 這也具有直接概括掉最后n
元素的優勢。
from itertools import tee, islice
def drop_last(it, n=1):
it, lookahead = tee(iter(it))
next(islice(lookahead, n, n), None)
for _ in lookahead:
yield next(it)
for x in drop_last([1, 2, 3]):
print(x)
# output:
# 1
# 2
這個怎么樣?
list1 = [3, 2, 3]
for i in list1[:-1]:
print(i)
如果不要求創建任何中間副本,則可以使用itertools.islice
:
import itertools
list1 = [3, 2, 3]
for i in itertools.islice(list1, len(list1) - 1)):
print(i)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.