>>> x=[("x1","x2","x3"),("x1","x2"),("x2","x3"),("x3","x4")]
>>> x
[('x1', 'x2', 'x3'), ('x1', 'x2'), ('x2', 'x3'), ('x3', 'x4')]
我想删除列表中的元组--x ,if len(x[id])==3 ,len(x[0]==3) ,所以它会被删除,[('x1', 'x2'), ('x2', 'x3'), ('x3', 'x4')] 是我的想要,我该如何编写代码?
[del element if len(element[id]==3) for id,element in enumerate(x)]
invalid syntax.
请您参考如下方法:
使用列表理解来过滤元素,保留所有长度不为 3 的元素:
x = [el for el in x if len(el) != 3]
演示:
>>> x = [('x1', 'x2', 'x3'), ('x1', 'x2'), ('x2', 'x3'), ('x3', 'x4')]
>>> [el for el in x if len(el) != 3]
[('x1', 'x2'), ('x2', 'x3'), ('x3', 'x4')]
