简体   繁体   中英

How to check how many of the last elements in a list are equal in python?

I am appending integers to a list one by one (using a loop) as so:

A.append(x) where x is an integer, which eventually gives for example:

A = [4, 8, 2, 4, 3, 7, 7, 7]

During every loop, ie just after each integer is added to the end of the array, I would like to check whether the same integer has been added a certain number of times (say, 3, in the example below) and throw an exception if so.

Pseudo code:

if somewayofcheckingA == 3:
    raise Exception("Lots of the latest integers are similar")

I could just do the below, but if I wanted to check for say, 100 repeats, then obviously the code would become a mess.

if A[-1] == A[-2] and A[-2] == A[-3]:
    raise Exception("Lots of the latest integers are similar")

Thanks!

Passing a list to set() will return a set with all unique values in the list. You can use slice notation to get a list of the last n values using the following

n = 3
if len(A) >= n and len(set(A[-n:])) == 1:
    raise Exception("Lots of the latest integers are similar")

if you just want to check just last 3 then this would do it.

limit = 3
if len(set(A[-limit:])) == 1:
    raise Exception("Lots of the latest integers are similar")

You could use collections.Counter() to count how many times the last element appears. For example:

occurrences = collections.Counter(A)
if occurrences[A[-1]] >= 3:
   raise Exception("Lots of the latest integers are similar")

Or an even simpler way

if A.count(A[-1]) >= 3:
   raise Exception("Lots of the latest integers are similar")

**THIS CODE CHECK FOR OCCURRENCES OF THE LAST ELEMENT AT ANY OTHER INDEX OF THE LIST

I did this for you. And I think this is some kind of pythonic.

class CustomList(list):
    def __init__(self, seq=()):
        self.last_equal_items = []
        super().__init__(seq)

    def append(self, some_item):
        if self.last_equal_items and some_item != self.last_equal_items[-1]:
            self.last_equal_items = []
        self.last_equal_items.append(some_item)
        if len(self.last_equal_items) >= 3:
            raise ValueError("Last equal items larger that 3")
        else:
            super(CustomList, self).append(some_item)

test = CustomList([])
test.append(1)
test.append(1)
test.append(1)
test.append(2)
test.append(1)
print(test)

You can just use CustomList like list . And it will alert when you insert the third equal value.

lists = [1,4,3,3];
def somewayofcheckingA(lists, a):
    lists.reverse()
    i = 0
    k = lists[0]
    count = 0
    while i < a:
        if(lists[i] == k):
            count= count+1
        i = i+1
    return count
        
print(test(lists, 3))

where lists is the list and a is the number of times you want to check

This answer is easy to follow and utilizes basic looping and conditional statements, which I think you should master before venturing into the other proposed solutions, which are more pythonic, but where you might get lost in the mix.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM