>>> x=[("x1","x2","x3"),("x1","x2"),("x2","x3"),("x3","x4")]
>>> x
[('x1', 'x2', 'x3'), ('x1', 'x2'), ('x2', 'x3'), ('x3', 'x4')]
我想要删除列表中的元组 - x,如果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.
答案 0 :(得分:6)
使用列表推导来过滤元素,保留所有不是长度为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')]