0

Is there a way to do something like this for each list in a numpy array without combining?:

for item, nextItem in zip(list,list[1::]): 

My numpy array:

    for i in range(0, len(list1), lines):
        array1 = np.array(list1[i:i+lines])

SAMPLE OUTPUT:

['23' '23' '23' '23']

['43' '43' '63' '43']

['43' '43' '43' '43']

I would like to step through the numpy array, to compare item/nextItem in each list without combining them? Zip is working for me on a regular list:

for item, nextItem in zip(list,list[1::]):
    if item != nextItem:
        #do stuff

Thanks in advance. Any insight would be appreciated.

mascot
  • 1
  • 1
  • Using numpy arr[:-1] != arr[1:] returns a boolean list, True where consecutive items in arr are different. np.where( arr[:-1] != arr[:1] ) returns a np.array of the indices for the Trues. What sort of processing do you need to do? – Tls Chris Feb 03 '21 at 12:30
  • For iterative processing like this, lists might well be faster, as well as easier. – hpaulj Feb 03 '21 at 19:18
  • Thank you for pointing me in the right direction...Trying to count and remove consecutive duplicates, keeping the same amount of lists. The sample result should be: [23] [43,63,43] [43] – mascot Feb 03 '21 at 21:50

1 Answers1

0

itertools.groupby counts consecutive duplicates in a list. Here it is applied to a list of lists:

from itertools import groupby
line = 0
list1 = [['23', '23', '23', '23'], ['43', '43', '63', '43'], ['43', '43', '43', '43']]

for x in list1:
    a = [[i, len([*group])] for i, group in groupby(list1[line])]
    line+=1
    print(a)

#RESULT:
    [['23', 4]]
    [['43', 2], ['63', 1], ['43', 1]]
    [['43', 4]]   

Counting consecutive duplicates of strings from a list

mascot
  • 1
  • 1
  • chain from itertools can also be used to flatten out the result lists: from itertools import chain; b = list(it.chain.from_iterable(a)); print(b) – mascot Feb 06 '21 at 12:33