通过将每个下一个列表与前一个列表进行比较并存储唯一列表来迭代 Python 中的列表列表

Iterating over list of lists in Python by comparing every next list with previous one and storing the unique lists

我在 python 中有一个列表列表,每个列表中有两个浮点值。我想迭代列表列表,但我希望将第一个列表存储在结果列表中,并将每个下一个列表与前一个列表进行比较,如果它与前一个列表不同,那么我再次需要将该列表存储在结果列表中.

list_of_lists = [[0.9953129999999999, 13.625421], [0.9953129999999999, 13.625421],[0.9953129999999999, 13.625421], [0.9953129999999999, 13.625421], [0.9953129999999999, 13.625421], [1.6215, 3.26078], [1.6215, 3.26078], [1.6215, 3.26078], [1.6215, 3.26078], [1.0, 12.25871], [1.0, 12.25871], [1.0, 12.25871], [1.0, 12.25871], [1.0, 12.25871], [1.0, 12.25871], [1.0, 12.25871], [1.0, 12.25871], [1.0, 12.25871], [1.0, 12.25871], [1.0, 12.25871], [1.0, 12.25871], [1.9050619999999998, 0.011995], [1.9050619999999998, 0.011995], [1.9050619999999998, 0.011995], [1.9050619999999998, 0.011995],[1.7293490000000002, 1.5182360000000001]]

我最初的做法是这样的;

resulting_list = []
resulting_list.insert(0,list_of_list[0])
print (resulting_list)
for index, rows in list_of_lists:
if ...

提前致谢!

您快完成了,您将第一个子列表放入了结果列表中。然后迭代剩余的项目,然后您可以检查当前子列表是否与结果列表中的最后一个子列表匹配,如果不匹配则添加此子列表。

list_of_lists = [[0.9953129999999999, 13.625421], [0.9953129999999999, 13.625421], [0.9953129999999999, 13.625421],
                 [0.9953129999999999, 13.625421], [0.9953129999999999, 13.625421], [1.6215, 3.26078], [1.6215, 3.26078],
                 [1.6215, 3.26078], [1.6215, 3.26078], [1.0, 12.25871], [1.0, 12.25871], [1.0, 12.25871],
                 [1.0, 12.25871], [1.0, 12.25871], [1.0, 12.25871], [1.0, 12.25871], [1.0, 12.25871], [1.0, 12.25871],
                 [1.0, 12.25871], [1.0, 12.25871], [1.0, 12.25871], [1.9050619999999998, 0.011995],
                 [1.9050619999999998, 0.011995], [1.9050619999999998, 0.011995], [1.9050619999999998, 0.011995],
                 [1.7293490000000002, 1.5182360000000001]]

resulting_list = [list_of_lists[0]]
for sub_list in list_of_lists[1:]:
    if sub_list != resulting_list[-1]:
        resulting_list.append(sub_list)
print(resulting_list)

输出

[[0.9953129999999999, 13.625421], [1.6215, 3.26078], [1.0, 12.25871], [1.9050619999999998, 0.011995], [1.7293490000000002, 1.5182360000000001]]

我觉得你找的是经典的"reduce"操作就行了。这样你就不需要 for 循环了:

import functools
def reducer(x,y):
    if(len(x)==0 or x[-1]!=y): return(x+[y])
    return(x)
functools.reduce(reducer, list_of_lists, list())

您从一个空列表开始作为累加器的初始值,如果新元素与上一个添加的元素不同,则继续添加新元素。

输出:

[[0.9953129999999999, 13.625421], [1.6215, 3.26078], [1.0, 12.25871], [1.9050619999999998, 0.011995], [1.7293490000000002, 1.5182360000000001]]

如果你想更简洁,你可以在调用中直接传递一个匿名 lambda 函数来减少

functools.reduce(lambda x, y: x+[y] if(len(x)==0 or x[-1]!=y) else x, list_of_lists, list())