How one could get all the elements in a list without an element at a certain index in a python list. Would be great if there is an fast and easy way of doing it.
Thanks
How one could get all the elements in a list without an element at a certain index in a python list. Would be great if there is an fast and easy way of doing it.
Thanks
认为
elements # list of values
n # unwanted element index
那么你可以做
result = elements[:n] + elements[n+1:]
或者
result = elements[:] # copy
del result[n]
除了切片还有另一种方法:
def exclude(iterable, index):
return [elem for i, elem in enumerate(iterable) if i != index]
那么,有什么好处呢?
好吧,它适用于任何可迭代的,而不仅仅是序列……但这没什么大不了的;当你处理生成器或字典时,你通常没有索引......(另外,你可以通过使用islice
而不是切片更容易地获得它。)
但是,很容易推广到多个索引,如果您可能想要的话,这可能是一件大事:
def exclude(iterable, *indices):
indices = set(indices)
return [elem for i, elem in enumerate(iterable) if i not in indices]
但是,如果您永远都不想这样做,那只是没有充分理由的额外复杂性,因此请使用切片。
>>> lst = ['a', 'b', 'c', 'd', 'e']
>>> exclude = lambda l, i: l[:i] + l[i+1:]
>>> exclude(lst, 3)
['a', 'b', 'c', 'e']