2
[
[0.074, 0.073, 0.072, 0.03, 0.029, 0.024, 0.021, 0.02], 
[0.02, 0.02, 0.015], 
[0.026, 0.026, 0.02, 0.02, 0.02, 0.015], 
[0.021, 0.021, 0.02, 0.017], [0.077, 0.076, 0.074, 0.055, 0.045, 0.021], 
[0.053, 0.052, 0.051, 0.023, 0.022], 
[0.016, 0.016]
]

以上是列表列表 data['stock'] 的输出。

我正在考虑删除每个子列表中的重复内容,但想不出办法。如果您看一下第 3 行,您会注意到存在三个元素(0.02、0.02 和 0.015)。但是,前 2 个元素实际上是重复的,因此其中一个元素是多余的。

有没有办法可以在每个子列表中进行检查以在保留订单的同时消除重复值?

请指教!

4

3 回答 3

3

看起来子列表已经排序,所以你可以申请itertools.groupby

In [1]: data = [
   ...: [0.074, 0.073, 0.072, 0.03, 0.029, 0.024, 0.021, 0.02], 
   ...: [0.02, 0.02, 0.015], 
   ...: [0.026, 0.026, 0.02, 0.02, 0.02, 0.015], 
   ...: [0.021, 0.021, 0.02, 0.017], [0.077, 0.076, 0.074, 0.055, 0.045, 0.021], 
   ...: [0.053, 0.052, 0.051, 0.023, 0.022], 
   ...: [0.016, 0.016]
   ...: ]

In [2]: from itertools import groupby

In [3]: [[k for k, g in groupby(subl)] for subl in data]
Out[3]: 
[[0.074, 0.073, 0.072, 0.03, 0.029, 0.024, 0.021, 0.02],
 [0.02, 0.015],
 [0.026, 0.02, 0.015],
 [0.021, 0.02, 0.017],
 [0.077, 0.076, 0.074, 0.055, 0.045, 0.021],
 [0.053, 0.052, 0.051, 0.023, 0.022],
 [0.016]]
于 2012-12-16T11:53:12.623 回答
1

使用OrderedDict的解决方案。这将适用于连续和非连续重复,同时保留顺序

>>> from collections import OrderedDict
>>> some_list = [
[0.074, 0.073, 0.072, 0.03, 0.029, 0.024, 0.021, 0.02],
[0.02, 0.02, 0.015],
[0.026, 0.026, 0.02, 0.02, 0.02, 0.015],
[0.021, 0.021, 0.02, 0.017], [0.077, 0.076, 0.074, 0.055, 0.045, 0.021],
[0.053, 0.052, 0.051, 0.023, 0.022],
[0.016, 0.016]
]
>>> [OrderedDict.fromkeys(e).keys() for e in some_list]
[[0.074, 0.073, 0.072, 0.03, 0.029, 0.024, 0.021, 0.02], [0.02, 0.015], [0.026, 0.02, 0.015], [0.021, 0.02, 0.017], [0.077, 0.076, 0.074, 0.055, 0.045, 0.021], [0.053, 0.052, 0.051, 0.023, 0.022], [0.016]]
于 2012-12-16T15:17:23.923 回答
0

简单的回答:

使用列表(设置(您的列表))。

Set 创建唯一元素,list() 将其转换为列表。

>>> lis1 = [1,2,3,4,4,3,2]
>>> print list(set(lis1))
[1, 2, 3, 4]
>>> 
于 2012-12-17T12:12:02.747 回答