给定这样一个列表,其中第一列是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是字典中的项数。这种复杂性大于所需的复杂性。你知道吗
这将返回嵌套列表,就像示例输出是嵌套列表一样。你知道吗
你可以用一套理解方法来做这件事,比如:
代码:
测试代码:
结果:
相关问题 更多 >
编程相关推荐