简体   繁体   中英

How to get minimum value in predefined set list (in python 3.x)?

How to get minimum value in predefined set list in python 3.x?

I have a list of data 'a'

a = {44.1, 78.2, 74.2, 85.4, 107.6, 167.7, 221.6, 245.2, 299.2, 314.5}

I wanted to get minimum value for 3 consecutive data range, starting from the last three, coming forward to the first three data.

Minimum value of last three (245.2, 299.2, 314.5), next three (221.6, 245.2, 299.2), next three (167.7, 221.6, 245.2) and so on until first three (44.1, 78.2, 74.2). The minimum values should become a list as well.

This is what I tried but failed.

i = list(range(-1, -10, -1))
value = min(a[i - 3:i])
print(value)

I got this error

TypeError: unsupported operand type(s) for -: 'list' and 'int'

at line 2.

Since sets are unordered, you should make a a list instead, which is an ordered data structure:

>>> a = [44.1, 78.2, 74.2, 85.4, 107.6, 167.7, 221.6, 245.2, 299.2, 314.5]

Since you want to start at the end, you need to also reverse this list:

>>> a = a[::-1]
>>> a 
[314.5, 299.2, 245.2, 221.6, 167.7, 107.6, 85.4, 74.2, 78.2, 44.1]

Then you can slice the list into groups of 3 and get the minimum for each group:

>>> [min(x) for x in zip(a, a[1:], a[2:])]
[245.2, 221.6, 167.7, 107.6, 85.4, 74.2, 74.2, 44.1]

Based on @RoadRunner answer:

You want a moving minimum of 3 consecutive numbers...

a = [44.1, 78.2, 74.2, 85.4, 107.6, 167.7, 221.6, 245.2, 299.2, 314.5]
a.reverse()
[min(a[i:i+3]) for i in range(0, len(a) - 2)]

With the -2 you ensure that you always have 3 numbers.

Start off using a Pandas DataFrame. One of the operations in a DataFrame is the idea of "rolling" (taking X at a time and doing something with it)

import pandas as pd
data = pd.DataFrame([44.1, 78.2, 74.2, 85.4, 107.6, 167.7, 221.6, 245.2, 299.2, 314.5])
answer = data.rolling(3).min()

If you want to start at the end just reverse the list (I know you have a set() there but that's not a good data structure for this)

This is one way using bottleneck.move_min :

from bottleneck import move_min

a = [44.1, 78.2, 74.2, 85.4, 107.6, 167.7, 221.6, 245.2, 299.2, 314.5]
a = a[::-1]

list(move_min(a, window=3)[2:])

# [ 245.2,  221.6,  167.7,  107.6,   85.4,   74.2,   74.2,   44.1]

The bottleneck algorithm is based on Richard Harter's O( n ) The minimum on a sliding window algorithm . An O(1) algorithm is also available .

Try this code ! Also I am attach the screenshot of the output .

a = [44.1, 78.2, 74.2, 85.4, 107.6, 167.7, 221.6, 245.2, 299.2, 314.5]
a.reverse()
ans=[]
for i in range(0,len(a)-2):
  ans.append(min(a[i:i+3]))
print(ans)

在此处输入图片说明

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