>>> 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.发布于 2014-03-27 13:12:46
使用列表理解来筛选元素,将所有内容保持在长度为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')]https://stackoverflow.com/questions/22688691
复制相似问题