[英]How to remove lists from a list
I have created a list where within it I seek to eliminate only the lists whose first value is greater than the second value of it.我创建了一个列表,在其中我试图仅消除第一个值大于它的第二个值的列表。
I tried creating a second list with the elements to remove but I think it is not the most optimal way.我尝试使用要删除的元素创建第二个列表,但我认为这不是最佳方式。
#y = []
x = [[1, 4], [1, 6], [2, 5], [2, 7], [4, 8], [6, 5], [6, 7], [2, 6], [3, 7], [5, 8], [6, 4], [7, 5]]
for i in range(len(x)):
if x[i][0] > x[i][1]:
print(x[i])
# y.append(x[i])
Is there an optimal way to achieve this?有没有实现这一目标的最佳方法?
I want that when printing on screen you get the following:我希望在屏幕上打印时得到以下信息:
[[1, 4], [1, 6], [2, 5], [2, 7], [4, 8], [6, 7], [2, 6], [3, 7], [ 5, 8]]
Best regards,此致,
This should work:这应该有效:
y = [[a,b] for a,b in x if a <= b]
Testing:测试:
>>> x = [[1, 4], [1, 6], [2, 5], [2, 7], [4, 8], [6, 5], [6, 7], [2, 6], [3, 7], [5, 8], [6, 4], [7, 5]]
>>> y = [[a,b] for a,b in x if a < b]
>>> y
[[1, 4], [1, 6], [2, 5], [2, 7], [4, 8], [6, 7], [2, 6], [3, 7], [5, 8]]
>>>
This modifies the original list:这会修改原始列表:
for i, (a, b) in enumerate(x):
if a > b:
del x[i]
Creating a new list:创建一个新列表:
[v for v in x if v[0] <= v[1]]
Or elimination in place:或就地消除:
for i in range(len(x) - 1, -1, -1): # need to start at the end
if x[i][0] > x[i][1]:
x.pop(i)
>>> filtered = list(filter(lambda f: f[0] < f[1], x))
>>> print(filtered)
This will create a new list with the desired values, using the built in filter(function, iterable)
function.这将使用内置的
filter(function, iterable)
function 创建一个具有所需值的新列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.