我有一个看起来像这样的数据结构:
[(1, 2), (2, 3), (4, 0), (5, 10), (6, 0), (7, 0)]
在第二个元素为 0 的列表末尾仅过滤掉元组的最佳方法是什么?
所需的输出是:
[(1, 2), (2, 3), (4, 0), (5, 10)]
在我看来,这听起来像是您想要一个“rstrip()
列表”。您可以使用.pop()
while 循环:
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)]
根据您的问题,我解释为您只想删除第二个值为 0 的元素。如果这不是您的意思,我深表歉意。您可以这样做(如果您想永久更改列表):
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