我有一个数据结构,长这样:
[(1, 2), (2, 3), (4, 0), (5, 10), (6, 0), (7, 0)]
仅过滤列表末尾第二个元素为0的元组的最佳方法是什么?
期望输出为:
[(1, 2), (2, 3), (4, 0), (5, 10)]
while somelist and somelist[-1][1] == 0:
somelist.pop()
这会直接修改列表。
如果要创建一个副本,你需要先找到一个切片终点,然后切片复制:
end = len(somelist)
while end and somelist[end - 1][1] == 0:
end -= 1
newlist = somelist[:end]
In [355]: list(reversed(list(dropwhile(lambda x: x[1]==0, reversed([(1, 2), (2, 3), (4, 0), (5, 10), (6, 0), (7, 0)])))))
Out[355]: [(1, 2), (2, 3), (4, 0), (5, 10)]
我更喜欢@MartijnPieters提出的原地解决方案。
>>> L = [(1, 2), (2, 3), (4, 0), (5, 10), (6, 0), (7, 0)]
>>> i = next((i for i, (x, y) in enumerate(reversed(L)) if y != 0), 0)
>>> L[:-i]
[(1, 2), (2, 3), (4, 0), (5, 10)]
myList = [(1, 2), (2, 3), (4, 0), (5, 10), (6, 0), (7, 0)]
for i in range(len(myList)):
if myList[i][1] == 0:
del myList[i]
return myList
或者如果您不想更改列表,可以这样做:
myList = [(1, 2), (2, 3), (4, 0), (5, 10), (6, 0), (7, 0)]
afterList = []
for i in myList:
if i[1] != 0:
afterList.append(i)
return afterList
IndexError
。 - Blenderfor i in range(len(mylist))
会循环太多次。 - Blender