对于仅排除一个元素,@Applet123 提出的 2 切片 lst[:i] + lst[i + 1:] 方法可能是最快的(或者可能是 excluded = lst.pop(1) 提取排除的元素,for x in lst: print(x) 用于打印所有其他元素;然后是 lst.insert(1,excluded)将排除的元素放回列表中。有关详细信息,请参阅data structures docs。
如果您只是想过滤掉某些索引,而不是 for 循环,我建议您使用基于 list comprehensions 和 enumerate 的更 Pythonic(和直观)的方法:
myList = [1,2,3,4,5,6,7,8,9]
excludedIndices = [1]
myFilteredList = [x for i, x in enumerate(myList) if i not in excludedIndices]
print (myFilteredList)
# output:
# [1,3,4,5,6,7,8,9]
# or, to actually print each element individually:
for x in myFilteredList:
print (x)
# which can also work as a 2-liner with inline filtering:
for i, x in enumerate(myList):
if i not in excludedIndices: print(x)
还可以查看 filter 和 map 内置函数的 python 用法,这对于此目的可能有点过头,但仍为此类处理提供了通用且更强大的解决方案:
# filters an enumerated element
def myFilter(element):
return element[0] not in excludedIndices
# maps an enumerated element to a function
def myMap(element):
print(element[1])
# runs myMap function for each enumerated element on the list filtered by myFilter
for x in map(myMap,filter(myFilter,enumerate(myList))): pass
您也可以使用lambda expressions 将其变成单线:
for x in map(lambda x: print(x[1]),filter(lambda x: x[0] not in excludedIndices,enumerate(myList))): pass