简体   繁体   English

从 Python 中的列表中删除包含相同元素的列表

[英]Removing a list containing the same elements from a list in Python

Is there a straightforward way to remove a list containing all elements the same instead of specifying the actual location?有没有一种简单的方法来删除包含所有相同元素的列表,而不是指定实际位置? For example, A[1] has to be removed because all the elements are the same?例如,必须删除A[1]因为所有元素都相同?

A=[[[1],[2],[2]],[[3],[3],[3]],[[4],[5],[4]]]
print(A)

A.remove(A[1])
print(A)

The output is and should be output 是并且应该是

[[[1],[2],[2]],[[4],[5],[4]]]

We can use a list comprehension here:我们可以在这里使用列表推导:

A = [[[1],[2],[2]],[[3],[3],[3]],[[4],[5],[4]]]
output = [x for x in A if min(x) != max(x)]
print(output)  # [[[1], [2], [2]], [[4], [5], [4]]]

We can identify a sublist as candidate for being removed by checking if the min and max values be the same.我们可以通过检查最小值和最大值是否相同来将子列表识别为被删除的候选者。 If those two values are not the same, then we retain the sublist.如果这两个值相同,那么我们保留子列表。

You can count number of equal items in list with list.count method.您可以使用 list.count 方法计算列表中相等项目的数量。 Considering that all elements of the A cannot be empty you can filter them like this.考虑到 A 的所有元素不能为空,您可以像这样过滤它们。

filtered = [el for el in A if el.count(el[0]) != len(el)]

Or to be sure that code will not throw the IndexError on empty items, you can check the length of an item.或者为了确保代码不会在空项目上抛出 IndexError,您可以检查项目的长度。

filtered = [el for el in A if len(el) and el.count(el[0]) != len(el)]

This approach will also works for strings and other types.这种方法也适用于字符串和其他类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM