Fed*_*ile 0 python list remove-if
我有一个像这样的项目列表:
A = [[0 A B],[1 C D],[2 E F],[3 G H],[4 I L],[5 M N],[6 O P],[7 Q R],[8 S T],[9 U Z]]
Run Code Online (Sandbox Code Playgroud)
然后我定义另一个列表,如下所示:
index = [0,2,6]
Run Code Online (Sandbox Code Playgroud)
我的目标是从A中删除列表1,3和7,结果是:
A = [[1 C D],[3 G H],[4 I L],[5 M N],[7 Q R],[8 S T],[9 U Z]]
Run Code Online (Sandbox Code Playgroud)
删除此类项目最明智的方法是什么?如果可能的话我想在不使用for循环的情况下制作它.
我尝试使用以下代码,但显然它不起作用,因为A的大小在每次迭代时都会受到影响
for j in index:
del A[j]
Run Code Online (Sandbox Code Playgroud)
最功能(和Pythonic)方式可能是创建一个新列表,省略原始列表中这些索引处的元素:
def remove_by_indices(iter, idxs):
return [e for i, e in enumerate(iter) if i not in idxs]
Run Code Online (Sandbox Code Playgroud)
在这里看到它.
| 归档时间: |
|
| 查看次数: |
548 次 |
| 最近记录: |