Find maximum with limited length in the list

I am looking for the maximum absolute value from a list.

For example, a list:

[1, 2, 4, 5, 4, 5, 6, 7, 2, 6, -9, 6, 4, 2, 7, 8]

I want to find the maximum with lookahead = 4. In this case, it will return me:

[5, 7, 9, 8]

How can I do this only in Python?

for d in data[::4]:
    if count < LIMIT:
        count = count + 1

        if abs(d) > maximum_item:
            maximum_item = abs(d)
    else:
        max_array.append(maximum_item)

        if maximum_item > highest_line:
            highest_line = maximum_item

        maximum_item = 0
        count = 1

I know I can use for a loop to test this. But I'm sure there is an easier way in python.

+4
source share
4 answers

Using standard Python:

[max(abs(x) for x in arr[i:i+4]) for i in range(0, len(arr), 4)]

This also works if the array cannot be divided equally.

+5
source

Match listwith abs(), then cutlist and send it to max():

array = [1,2,4,5,4,5,6,7,2,6,-9,6,4,2,7,8]
array = [abs(item) for item in array]
# use linked question answer to chunk
# array = [[1,2,4,5], [4,5,6,7], [2,6,9,6], [4,2,7,8]] # chunked abs()'ed list
values = [max(item) for item in array]

Result:

>>> values
[5, 7, 9, 8]
+4
source

islice itertools module:

>>> from itertools import islice
>>> [max(islice(map(abs,array),i,i+4)) for i in range(0,len(array),4)]
[5, 7, 9, 8]

:

1 - map(abs, array)
2 - islice(map(abs,array),i,i+4))
3 - i in range(0,len(array),4) islice,

:

def max_of_chunks(lst, chunk_size):
    lst = map(abs, lst)
    result = [max(islice(lst,i,i+chunk_size)) for i in range(0,len(lst),chunk_size)]
    return result
0

: , . , :) . , :

largest = [max(abs(x) for x in l[i:i+n]) for i in xrange(0, len(l), n)]

largest = [max(abs(x) for x in l[i:i+n]) for i in range(0, len(l), n)]

Python3.


: ( ) , , numpy . , Python. (- ).

, :

In [1]: l = [1, 2, 4, 5, 4, 5, 6, 7, 2, 6, -9, 6, 4, 2, 7, 8]
In [2]: n = 4

A. , set. , sort N () :

In [3]: sorted(list(set(l)))[-n:]
Out[3]: [5, 6, 7, 8]

B. heapq:

In [7]: import heapq

In [8]: heapq.nlargest(n, set(l))
Out[8]: [8, 7, 6, 5]

Of course, you can “wrap” a technique A or B into some kind of function convenient for a person, for example def get_largest(seq, n): return sorted(list(set(l)))[-n:]. Yes, I commented on some details, for example, the appeal IndexError. You must keep this in mind when writing code.

C. If your list is very long and you need to perform many of these operations as fast as Python, you should use special third-party libraries such as numpyor bottleneck.

0
source

Source: https://habr.com/ru/post/1622323/


All Articles