Number of iterations of the most consecutive number in the Python list

Asked 2 years ago, Updated 2 years ago, 14 views

For example, in the list, [2,2,2,4,4,5,6,1,1,1,1,1,2,3,1,4]

It's like this.

The number that repeats the most in a row is 1 that repeats 5 times, I want to say that the output is five, but what should I do? I don't know how to give you the terms.

python

2022-09-20 17:27

2 Answers

Hello, the conditions are compared by the index number li[i] == li[i+1] or li[i-1] == li[i].

li = [2, 2, 2, 4, 4, 5, 6, 1, 1, 1, 1, 1, 2, 3, 1, 4]
max_count = 0
count = 0
for i in range(0, len(li)-1):
    if li[i] == li[i+1]:
        count += 1
    else:
        if max_count < count:
            max_count = count
            count = 0
print(max_count)

Or

li = [2, 2, 2, 4, 4, 5, 6, 1, 1, 1, 1, 1, 2, 3, 1, 4]
max_count = 0
count = 0
for i in range(0, len(li)-1):
    if li[i] == li[i+1]:
        count += 1
    else:
        if max_count < count:
            max_count = count
            max_num = li[i]
            count = 0
print(str(max_num) + " came out continuously" + str(max_count) + ".")


2022-09-20 17:27

List(2,2,2,4,4,5,6,1,1,1,1,1,2,3,1,4).groupBy(identity).mapValues(_.size).maxBy(_._2)
// (1,6) // 1 has 6

List(2,2,2,4,4,5,6,1,1,1,1,1,2,3,1,4).groupBy(identity).mapValues(_.size).maxBy(_._2)._2
// 6


2022-09-20 17:27

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.