从 2D 列表中获取唯一元素 [英] Get unique elements from a 2D list

查看:43
本文介绍了从 2D 列表中获取唯一元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样创建的 2D 列表:

I have a 2D list which I create like so:

Z1 = [[0 for x in range(3)] for y in range(4)]

然后我继续填充这个列表,使得 Z1 看起来像这样:

I then proceed to populate this list, such that Z1 looks like this:

[[1, 2, 3], [4, 5, 6], [2, 3, 1], [2, 5, 1]]

我需要提取Z1唯一 1x3元素,不考虑顺序:

I need to extract the unique 1x3 elements of Z1, without regard to order:

Z2 = makeUnique(Z1) # 解决方法

Z2 的内容应该是这样的:

The contents of Z2 should look like this:

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

如您所见,我认为 [1, 2, 3][2, 3, 1] 是重复的,因为我不关心订购.

As you can see, I consider [1, 2, 3] and [2, 3, 1] to be duplicates because I don't care about the order.

另请注意,单个数值可能会在元素中出现多次(例如 [2, 3, 1][2, 5, 1]);只有当所有三个值一起出现不止一次(以相同或不同的顺序)时,我才认为它们是重复的.

Also note that single numeric values may appear more than once across elements (e.g. [2, 3, 1] and [2, 5, 1]); it's only when all three values appear together more than once (in the same or different order) that I consider them to be duplicates.

我搜索了几十个类似的问题,但似乎没有一个能解决我的确切问题.我是一个完整的 Python 初学者,所以我只需要朝着正确的方向努力.

I have searched dozens of similar problems, but none of them seems to address my exact issue. I'm a complete Python beginner so I just need a push in the right direction.

我已经试过了:

Z2= dict((x[0], x) for x in Z1).values()Z2= set(i for j in Z2 for i in j)

但这不会产生预期的行为.

But this does not produce the desired behaviour.

非常感谢您的帮助!

路易斯·瓦兰斯

推荐答案

如果子列表中元素的顺序无关,您可以使用以下方法:

If the order of the elements inside the sublists does not matter, you could use the following:

from collections import Counter

z1 = [[1, 2, 3], [4, 5, 6], [2, 3, 1], [2, 5, 1]]

temp = Counter([tuple(sorted(x)) for x in z1])

z2 = [list(k) for k, v in temp.items() if v == 1]
print(z2)  # [[4, 5, 6], [1, 2, 5]]

一些说明:

  • 排序使示例中的列表 [1, 2, 3][2, 3, 1] 相等,因此它们按 Counter<分组/code>
  • 转换为 tuplelist 转换为可散列的内容,因此可以用作 dictionary 键.
  • Counter 创建一个 dict ,上面创建的 tuple 作为键,值等于它们在原始list
  • 最终的 list-comprehensionCounter 字典 中获取所有计数为 1 的键.
  • sorting makes lists [1, 2, 3] and [2, 3, 1] from the example equal so they get grouped by the Counter
  • casting to tuple converts the lists to something that is hashable and can therefore be used as a dictionary key.
  • the Counter creates a dict with the tuples created above as keys and a value equal to the number of times they appear in the original list
  • the final list-comprehension takes all those keys from the Counter dictionary that have a count of 1.

如果顺序确实很重要,您可以改用以下内容:

If the order does matter you can use the following instead:

z1 = [[1, 2, 3], [4, 5, 6], [2, 3, 1], [2, 5, 1]]

def test(sublist, list_):
    for sub in list_:
        if all(x in sub for x in sublist):
            return False
    return True

z2 = [x for i, x in enumerate(z1) if test(x, z1[:i] + z1[i+1:])]
print(z2)  # [[4, 5, 6], [2, 5, 1]]

这篇关于从 2D 列表中获取唯一元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆