Python 如何制作一组列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26783326/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 01:00:32  来源:igfitidea点击:

How to make a set of lists

pythonlistset

提问by Phani

I have a list of lists like this:

我有一个像这样的列表:

i = [[1, 2, 3], [2, 4, 5], [1, 2, 3], [2, 4, 5]]

I would like to get a list containing "unique" lists (based on their elements) like:

我想得到一个包含“独特”列表(基于它们的元素)的列表,例如:

o = [[1, 2, 3], [2, 4, 5]]

I cannot use set()as there are non-hashable elements in the list. Instead, I am doing this:

我无法使用,set()因为列表中有不可散列的元素。相反,我正在这样做:

o = []
for e in i:
  if e not in o:
    o.append(e)

Is there an easier way to do this?

有没有更简单的方法来做到这一点?

采纳答案by u1860929

You can create a set of tuples, a set of lists will not be possible because of non hashable elements as you mentioned.

您可以创建一组元组,由于您提到的不可散列元素,因此无法创建一组列表。

>>> l = [[1, 2, 3], [2, 4, 5], [1, 2, 3], [2, 4, 5]]
>>> set(tuple(i) for i in l)
{(1, 2, 3), (2, 4, 5)}

回答by boh717

You can convert each element to a tuple and then insert it in a set.

您可以将每个元素转换为元组,然后将其插入到集合中。

Here's some code with your example:

这是您的示例的一些代码:

tmp = set()
a = [[1, 2, 3], [2, 4, 5], [1, 2, 3], [2, 4, 5]]
for i in a:
    tmp.add(tuple(i))

tmpwill be like this:

tmp将是这样的:

{(1, 2, 3), (2, 4, 5)}

回答by Padraic Cunningham

i = [[1, 2, 3], [2, 4, 5], [1, 2, 3], [2, 4, 5]]

print([ele for ind, ele in enumerate(i) if ele not in i[:ind]])
[[1, 2, 3], [2, 4, 5]]

If you consider [2, 4, 5]to be equal to [2, 5, 4]then you will need to do further checks

如果您认为[2, 4, 5]等于[2, 5, 4]那么您将需要做进一步的检查

回答by sohrab haghayegh

Here's another way to do it:

这是另一种方法:

I = [[1, 2, 3], [2, 4, 5], [1, 2, 3], [2, 4, 5]]
mySet = set()

for j in range(len(I)):
  mySet = mySet | set([tuple(I[j])])

print(mySet)