我有一个包含数百万其他列表的嵌套(使用元组atm)。对于每个列表,一个元素只能包含一次。我以为每个列表都是唯一的,所以我都需要它们,但是最近我意识到嵌套列表包含这样的对:
listA = ('77', '131', '212', '69')
listB = ('69', '212', '131', '77')
虽然listA和listB是唯一的,但一个只是另一个的反向副本。我需要保留每个唯一的组合,因为顺序很重要。
listC = ('131', '69', '77', '212')
因此,listC在使用相同元素时由于顺序而被认为是唯一的,因此需要保留。
如果删除所有重复项,则可以减少大量嵌套嵌套列表(大约一半),但是我找不到一种省时的方法。
因为最好在将这些反向重复添加到嵌套列表之前消除这些反向重复,所以在下面列出了用于创建列表的类。
class Graph(object):
def __init__(self, graph_dict=None):
""" Initializes a graph object.
If no dictionary or None is given,
an empty dictionary will be used. """
if graph_dict == None:
graph_dict = {}
self.__graph_dict = graph_dict
def find_all_paths(self, start_vertex, end_vertex, path=[]):
""" Find all paths from start_vertex to end_vertex in graph """
graph = self.__graph_dict
path = path + [start_vertex]
if start_vertex == end_vertex:
return [path]
if start_vertex not in graph:
return []
paths = []
for vertex in graph[start_vertex]:
if vertex not in path:
extended_paths = self.find_all_paths(vertex, end_vertex, path)
for p in extended_paths:
if len(p) >= 2:
p = tuple(p)
paths.append(p)
return paths
graph = Graph(vertexGraphDict)
nestedList= graph.find_all_paths(begin, end)
vertexGraphDict只是一个作为键的顶点字典,其值是与其连接的其他顶点的列表。
我尝试使用以下方法消除反向重复:
reversedLists = []
for item in nestedLists:
if item in reversedLists:
nestedLists.remove(item)
else:
revItem = item[::-1]
reversedLists.append(revItem)
这种方法很慢。在删除类中的行p = tuple(p)之后,我还尝试了revItem = list(reversed(item));也很慢 在清单制作过程中尝试这些方法可节省总体时间,但不会加快消除过程的速度,这是关键。
OrderedDict
仅当最后一项低于第一项且值是元组本身时,才可以按相反的顺序构建键为元组的,然后获取的值列表OrderedDict
:
from collections import OrderedDict
l = [
('77', '131', '212', '69'),
('69', '212', '131', '77'),
('1', '2', '3', '4'),
('4', '1', '2', '3'),
('4', '3', '2', '1')
]
list(OrderedDict((t[::-1] if t[-1] < t[0] else t, t) for t in l).values())
或者,如果您使用的是dict键排序的Python 3.7或更高版本,则可以使用dict代替OrderedDict
:
list({t[::-1] if t[-1] < t[0] else t: t for t in l}.values())
返回:
[('69', '212', '131', '77'), ('4', '3', '2', '1'), ('4', '1', '2', '3')]
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句