通过比较每个下一个列表与上一个列表并存储唯一列表来遍历Python中的列表列表

问题描述 投票:0回答:1

我在python中有一个列表列表,每个列表中都有两个float值。我想遍历列表的列表,但是我希望将第一个列表存储在结果列表中,并将每个下一个列表与上一个列表进行比较,如果它与前一个列表不同,那么我再次需要将该列表存储在结果列表中。

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 ...

提前感谢!

python-3.x list loops compare store
1个回答
0
投票

您快到了,您将第一个子列表放在结果列表中。然后遍历其余项,然后可以检查当前子列表是否与结果列表中的最后一个子列表匹配,如果不匹配,则将该子列表添加为广告。

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]]
© www.soinside.com 2019 - 2024. All rights reserved.