![](/img/trans.png)
[英]Python remove sublist in a list if specific element inside this sublist
[英]remove sublist if it contains a specific value
如果它包含特定值,我如何删除完整的子列表?
A=[["A","no","yes","small"],
["B","yes","no","medium"],
["C","yes","yes","large"],
["D","yes","yes","small"],
["E","yes","no","medium"],
["F","yes","yes","small"]]
#find the index of each sublist with the value "small"
small=[]
for x in A:
if "small" in x:
small.append(A.index(x))
print(small)
#Output:
#[0, 3, 5]
#Desired output:
[["B","yes","no","medium"],
["C","yes","yes","large"],
["E","yes","no","medium"]]
如何删除所有值小的子列表?
鉴于您需要从列表中迭代和删除项目,最好的办法是使用 Python 的列表理解。
列表理解为您提供了一种在给定某些条件的情况下过滤现有列表的方法。 在您的情况下,您只需要列表A
中不包含字符串"small"
的项目(在本例中为列表)。 那么,下一个就是针对您的问题的一个简单解决方案。
A = [["A", "no", "yes", "small"],
["B", "yes", "no", "medium"],
["C", "yes", "yes", "large"],
["D", "yes", "yes", "small"],
["E", "yes", "no", "medium"],
["F", "yes", "yes", "small"]]
solution = [sublist for sublist in A if "small" not in sublist]
print(solution)
上面的列表理解可以理解为:创建一个新列表,其中的元素仅在A
中不包含"small"
字符串时才包含。
确实,在您的问题中,您询问如何在满足特定条件的情况下从列表中删除项目。 然而,这可能会导致错误,具体取决于它的实现方式,因为在迭代时,当您确实删除一个元素时,列表中的所有元素都将“向左”移动一个 position,使您在途中跳过其中一些。 例如,一个可能的解决方案可能是这样的:
for index, sublist in enumerate(A):
if "small" in sublist:
A.pop(index)
在您的示例中,这给出了正确答案,但它仍然是一个错误。 例如,我们可以检查如果第二个子列表包含字符串"small"
,那么它将跳过它。
small = [x for x in A if 'small' not in x]
print(small)
Output:
[['B', 'yes', 'no', 'medium'],
['C', 'yes', 'yes', 'large'],
['E', 'yes', 'no', 'medium']]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.