it_*_*ure 1 python list-comprehension list idiomatic
>>> x=[("x1","x2","x3"),("x1","x2"),("x2","x3"),("x3","x4")]
>>> x
[('x1', 'x2', 'x3'), ('x1', 'x2'), ('x2', 'x3'), ('x3', 'x4')]
Run Code Online (Sandbox Code Playgroud)
我想删除列表中的元组 - 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.
Run Code Online (Sandbox Code Playgroud)
使用列表推导来过滤元素,保持所有不是长度3:
x = [el for el in x if len(el) != 3]
Run Code Online (Sandbox Code Playgroud)
演示:
>>> 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')]
Run Code Online (Sandbox Code Playgroud)