python - Python: remove elements of a list satisfying a condition
问题描述
Given a Python list, I'd like to remove "bad" elements. For example, given a list of lists of integers, I'd like to remove lists beginning with a negative integer. Here's an attempt and failure:
S=[[1,1],[2,1],[-1,1],[-2,1]]
for s in S:
if s[0]<0:
S.remove(s)
which returns
[[1, 1], [2, 1], [-2, 1]]
I'd like to know why the above code doesn't work as expected (it would be instructive), as well as the right way to do this. (I know that I can create a new list where I add those lists of S with positive first element, but I'd rather not make a new list unless necessary.)
解决方案
推荐阅读
- python - 从 Java 到 python 的 POST 请求重制为空
- linux - 如何从触摸屏读取硬件级事件信息?
- html - 如何使用谷歌脚本在 web 应用程序(如 msg 框)上获取输入信息
- angular - 内容类型“application/x-www-form-urlencoded”的编码对象
- java - Java找不到本机库路径
- colors - 如何在 MPS 上下文编辑器中设置条件颜色?
- javascript - 同步加载外部 JavaScript
- r - 强制引入的 NA(无缺失值)
- android - 从缓存的视频 ExoPlayer 中获取 uri
- django - 如何让 TextField 在 DRF 的 API 浏览器中呈现?