查找列表中的不同元素

时间:2018-03-18 07:14:25

标签: python list time-complexity distinct

给定这样的列表,其中第一列是id,第二列是字符串,

x = [ [1, ["cat","dog"]],
      [2, ["dog", "mouse", "elephant"]],
      [3, ["mouse", "giraffe"]] ]

我想知道一种有效地将所有不同元素分组到另一个列表中的方法。

我的问题是因为我必须满足复杂性要求。

O(UCK),其中U是列表中的项目数,C是任何动物中的最大字符数,K是列表中动物的最大数量。

示例输出:

[ ["cat"],
  ["dog"],
  ["mouse"],
  ["elephant"],
  ["giraffe"] ]

我的解决方案使用字典来执行此操作:

distinctList = []
distinctDict = {}
for item in x:
     for animal in item[1]:
         if animal not in distinctDict:
              distinctList.append(animal)
              distinctDict[animal] = 1

然而,这种情况的复杂性将变为O(UKN),其中N是字典中的项目数。这种复杂性大于所需的复杂性。

3 个答案:

答案 0 :(得分:3)

您可以通过以下设置理解来实现:

代码:

uniques = {animal for row in data for animal in row[1]}

测试代码:

data = [[1, ["cat", "dog"]],
        [2, ["dog", "mouse", "elephant"]],
        [3, ["mouse", "giraffe"]]]

uniques = {animal for row in data for animal in row[1]}
print(uniques)

结果:

{'cat', 'giraffe', 'mouse', 'dog', 'elephant'}

答案 1 :(得分:0)

这将返回一个嵌套列表,就像您的示例输出是嵌套列表一样。

//redirect("rate/index?status=tambah_success","refresh");

答案 2 :(得分:0)

In [126]: data = [[1, ["cat", "dog"]],
     ...:         [2, ["dog", "mouse", "elephant"]],
     ...:         [3, ["mouse", "giraffe"]]]       

In [127]: [[x] for x in {animal for row in data for animal in row[1]}]
Out[127]: [['giraffe'], ['mouse'], ['elephant'], ['cat'], ['dog']]