在lis中寻找不同的元素

2024-10-01 22:38:48 发布

您现在位置:Python中文网/ 问答频道 /正文

给定这样一个列表,其中第一列是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是字典中的项数。这种复杂性大于所需的复杂性。你知道吗


Tags: in列表for字典itemcat复杂性动物
3条回答

这将返回嵌套列表,就像示例输出是嵌套列表一样。你知道吗

#!python2

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

for sublst in x:
    for subsublst in sublst[1]:
        if not any(subsublst in sublst for sublst in new_lst):
            new_lst.append([subsublst]) # nested list
            # new_lst.append(subsublst) # a list of strings
print new_lst

'''
[['cat'], ['dog'], ['mouse'], ['elephant'], ['giraffe']]
'''
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']]

你可以用一套理解方法来做这件事,比如:

代码:

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'}

相关问题 更多 >

    热门问题