如何从列表列表中删除包含重复值的列表:

时间:2019-03-29 09:45:24

标签: python-3.x

我需要从此列表中删除“重复项”:

[[4, 1], [1, 4], [0, 5], [5, 0]]

例如:[4, 1] [1, 4]是同一对象,我需要删除其中一个。 不使用列表理解工具怎么办?

3 个答案:

答案 0 :(得分:1)

一种方法是对它进行排序,如果没有出现在最终列表中,则附加在后面,如LogicalBranch在答案中提到的那样。

您提到您不能使用sort,并且列表中始终有2个元素。然后,您可以通过制作另一个与列表相反的列表并在最终答案中进行比较来做一个简单的技巧。参见下面的代码

ans = []
l = [[4, 1], [1, 4], [0, 5], [5, 0]]
for x in l:
    a = x[::-1]
    if x not in ans and a not in ans:
        ans.append(x)

print(ans) # [[4, 1], [0, 5]]

答案 1 :(得分:1)

根据评论,您不想使用list comprehensionsort,并且子列表中始终有2个元素,那么以下方法会有所帮助,

遍历列表并反转子列表,并检查它们是否出现在new_list

x = [[4, 1], [1, 4], [0, 5], [5, 0]]

new_list = []
for i in x:
    if i[::-1] not in new_list and i not in new_list:
        new_list.append(i)

print(new_list)

输出:

[[4, 1], [0, 5]]

答案 2 :(得分:0)

最简单的方法(不导入任何内容)是通过对列表中的每一对进行排序,然后再将其添加到新的结果列表中,如下所示:

result = []
for pair in [[4, 1], [1, 4], [0, 5], [5, 0]]:
  pair.sort()
  if pair not in result:
    result.append(pair)
print(result)

您甚至可以将其转换为函数:

def list_filter(collection):
  result = []
  for pair in collection:
    pair.sort()
    if pair not in result:
      result.append(pair)
  return result

然后您将这样使用:

list_filter([[4, 1], [1, 4], [0, 5], [5, 0]])

哪个应返回如下列表:

[[1, 4], [0, 5]]

您可以使用以下方法将其缩小:

list_filter = lambda collection: list(set([sorted(x) for x in collection]))

应该返回相同的结果。

编辑:未排序的更新方法:

(result, collection) = ([], [[4, 1], [1, 4], [0, 5], [5, 0]])

def check(n1, n2):
  for pair in collection:
    if n1 in pair and n2 in pair and sorted(pair) in collection:
      return True
  return False

for pair in collection:
  pair.sort()
  if pair not in result:
    result.append(pair)

print(result)

您甚至可以将其转换为函数:

def new_filter_function(collection):
  result = []

  def check(n1, n2):
    for pair in collection:
      if n1 in pair and n2 in pair and ([n1, n2] in collection or [n2, n1] in collection):
        return True
    return False

  for pair in collection:
    if pair not in result:
      result.append(pair)

  return result

然后您将这样使用:

new_filter_function([[4, 1], [1, 4], [0, 5], [5, 0]])

还应该返回如下列表:

[[1, 4], [0, 5]]

祝你好运。

相关问题