>> x [('x1', 'x2', 'x3'), ('x1', 'x2')-6ren">
gpt4 book ai didi

python - 如何有条件地从元组列表中删除元素?

转载 作者:太空宇宙 更新时间:2023-11-04 08:10:50 25 4
gpt4 key购买 nike

>>> 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')]

关于python - 如何有条件地从元组列表中删除元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22688691/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com