Comparing adjacent elements in list python

Python list removes data adjacent repeats [only one]

Refer to information://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]

The Python list finds the same element value of the adjacent elements [understand M = a [1:] n = a [: - 1] After the front-rear data to be compared, you can easily play neighbor elements. ]

Reference://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]

It is also possible to compare whether the adjacent elements are equal, that is, the above variable C is obtained, and then the following steps are performed.

Reference://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

Video liên quan

Chủ Đề