Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/330.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 从列表末尾筛选元素_Python_List_Filter - Fatal编程技术网

Python 从列表末尾筛选元素

Python 从列表末尾筛选元素,python,list,filter,Python,List,Filter,我的数据结构如下所示: [(1, 2), (2, 3), (4, 0), (5, 10), (6, 0), (7, 0)] 在第二个元素为0的列表末尾,只过滤掉元组的最佳方法是什么 所需输出为: [(1, 2), (2, 3), (4, 0), (5, 10)] 根据您的问题,我解释为您只想删除第二个值为0的元素。如果这不是你的意思,我道歉。 您可以这样做(如果要永久更改列表): 或者,如果不想更改列表,可以执行以下操作: myList = [(1, 2), (2, 3), (4, 0),

我的数据结构如下所示:

[(1, 2), (2, 3), (4, 0), (5, 10), (6, 0), (7, 0)]
在第二个元素为0的列表末尾,只过滤掉元组的最佳方法是什么

所需输出为:

[(1, 2), (2, 3), (4, 0), (5, 10)]

根据您的问题,我解释为您只想删除第二个值为0的元素。如果这不是你的意思,我道歉。 您可以这样做(如果要永久更改列表):

或者,如果不想更改列表,可以执行以下操作:

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

这听起来像是你想要一个“
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]

我更喜欢@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)]

你如何定义“列表的末尾”?(6,0)不在列表的末尾。您的第一个示例将生成一个
索引器
。这将删除OP想要保留的元素。@foriInRangeAsome:运行它。您的循环会从列表中删除元素,因此
for i in range(len(mylist))
将循环太多次。更不用说我意识到了示例的错误所在。当数字被删除时,列表的长度会发生变化。对不起。
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)]
>>> 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)]