从python上的列表中删除坐标 [英] Removing coordinates from list on python

查看:337
本文介绍了从python上的列表中删除坐标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在Python中创建了一个充满坐标"的列表:L1 = [(1,2,2,(5,6),(-1,-2),(1,-2)等.]

I have created a list full of "coordinates" in Python: L1 = [(1,2), (5,6), (-1,-2), (1,-2), etc..].

如果我想删除列表中所有包含负数的项目,我该怎么做?

If I wanted to remove all items in the list which contained negative numbers, how would I do this?

我尝试过:

for (a,b) in L1:
  if a < 0 or b < 0:
    L1.remove(a,b)

但是它不起作用.非常感谢您的帮助.

But it isn't working. Would very much appreciate any help.

杰克

推荐答案

在迭代过程中无法更改某些内容.结果很奇怪,违反直觉,几乎从来没有想要的结果.实际上,许多集合都明确禁止这样做(例如,集合和字典).

You cannot change something while you're iterating it. The results are weird and counter-intuitive, and nearly never what you want. In fact, many collections explicitly disallow this (e.g. sets and dicts).

相反,遍历一个副本(对于a [:]中的e:...),或者,而不是修改现有列表,对其进行过滤以获取包含所需项目的新列表([e for e in a如果 ...]).请注意,在许多情况下,您无需再次进行迭代即可进行过滤,只需将过滤与数据生成合并即可.

Instead, iterate over a copy (for e in a[:]: ...) or, instead of modifying an existing list, filter it to get a new list containing the items you want ([e for e in a if ...]). Note that in many cases, you don't have to iterate again to filter, just merge the filtering with the generation of the data.

L2 = []
for (a,b) in L1:
  if a >= 0 and b >= 0:
    L2.append((a,b))

L1 = L2
print L1

这篇关于从python上的列表中删除坐标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆