python 列表去除相邻重复相等数据(只保留一个)
参开资料:https://stackoverflow.com/questions/3460161/remove-adjacent-duplicate-elements-from-a-list
1 In [1]: import itertools
2
3 In [2]: a=[0, 1, 3, 2, 4, 4, 5, 6, 7, 8, 10, 11, 12, 13, 14, 16, 16, 17, 18, 18, 19, 20, 20, 21, 22, 22, 22, 23, 23, 23, 26, 29, 29, 30, 32, 33, 34, 32, 32, 15, 24]
4
5 In [3]: b=[k for k, _ in itertools.groupby(a)]
6
7 In [4]: print(b)
8 [0, 1, 3, 2, 4, 5, 6, 7, 8, 10, 11, 12, 13, 14, 16, 17, 18, 19, 20, 21, 22, 23, 26, 29, 30, 32, 33, 34, 32, 15, 24]
python 列表找到相邻元素相同的元素值(理解了 m=a[1:] n=a[:-1] 得到的就是要比较的前后数据之后,你就可以轻松地做玩转相邻元素啦)
参考资料:https://stackoverflow.com/questions/23452422/how-to-compare-corresponding-positions-in-a-list
1 In [22]: import numpy as np
2
3 In [23]: a=[0, 1, 3, 2, 4, 4, 5, 6, 7, 8, 10, 11, 12, 13, 14, 16, 16, 17, 18, 18, 19, 20, 20, 21, 22, 22, 22, 23, 23, 23, 26, 29, 29, 30, 32, 33, 34, 32, 32, 15, 24]
4
5 In [24]: m=a[1:]
6
7 In [25]: n=a[:-1]
8
9 In [26]: len(a)
10 Out[26]: 41
11
12 In [27]: len(m)
13 Out[27]: 40
14
15 In [28]: len(n)
16 Out[28]: 40
17
18 In [29]: c=[i[0]==i[1] for i in zip(m, n)]
19
20 In [30]: print(c)
21 [False, False, False, False, True, False, False, False, False, False, False, False, False, False, False, True, False, False, True, False, False, True, False, False, True, True, False, True, True, False, False, True, False, False, False, False, False, True, False, False]
22
23 In [31]: d=np.array(a[:-1])[c]
24
25 In [32]: print(d)
26 [ 4 16 18 20 22 22 23 23 29 32]
27
28 In [33]: result = list(set(d))
29
30 In [34]: result
31 Out[34]: [32, 4, 16, 18, 20, 22, 23, 29]
也可以用以下的方法比较出相邻元素是否相等,即求出上面的变量 c,然后再执行后面的步骤
参考资料:https://stackoverflow.com/questions/36343688/check-if-any-adjacent-integers-in-list-are-equal
1 In [35]: import operator
2
3 In [36]: import itertools
4
5 In [37]: c2=list(map(operator.eq, a, itertools.islice(a, 1, None)))
6
7 In [38]: print(c2)
8 [False, False, False, False, True, False, False, False, False, False, False, False, False, False, False, True, False, False, True, False, False, True, False, False, True, True, False, True, True, False, False, True, False, False, False, False, False, True, False, False]
9
10 In [39]: c==c2
11 Out[39]: True
python 比较列表相邻元素(找相同或去重)(python compare adjacent elements in list for finding the same or repeat)
原文:https://www.cnblogs.com/ttweixiao-IT-program/p/14278981.html