0

The result of an iteration produces:

93
93
93
93
...
96
96
96
108
and so on

I want to compare the first number to the next, e.g., (93, 93) - result True, True, True etc then (93,96) result False and so on.

To do this I made the following, with result:

93 93
93 93
93 93
93 93
93 96

It works but looks clunky. Is there a better way?

lst = []

def a_function(item):
    l = len(item) # in this case the item is an np array, and need its length
    tups = list(zip([l], [l][:1] + [l][1:]))
    lst.append(tups)
    a = lst[0][0][1]
    b = lst[-1][0][0]

    if a == b:
        return True
    else:
        return False

The examples Ive seen start with a list a =[1,1,1,1,2,2.....], where I need to create this. Tks

riot12
  • 63
  • 4

1 Answers1

0

You can use the built-in zip function to iterate over pairs of adjacent items in the sequence.
For example:

numbers = [93, 93, 93, 93, 96, 96, 96, 108]

for current, next in zip(numbers, numbers[1:]):
    print(current, next, current == next)

This will produce the following output:

93 93 True
93 93 True
93 93 True
93 93 True
93 96 False
96 96 True
96 96 True
96 108 False

Here, the zip function takes two arguments: the numbers list and a slice of that list starting at index 1 (numbers[1:]). The slice creates a new list that contains all the items in numbers except for the first one. The zip function then iterates over pairs of items from these two lists.

In each iteration of the loop, the current variable contains the current item in the sequence, and the next variable contains the next item. The expression current == next compares these two items, and the result is printed along with the current and next items.

I hope this helps! Let me know if you have any further questions.

Ertersy
  • 41
  • 5