[英]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? 如何在python 3.x中的预定义集合列表中获得最小值?
I have a list of data 'a' 我有一个数据列表“ 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. 我想获得连续3个数据范围的最小值,从最后三个开始,一直到前三个数据。
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). 前三个(245.2、299.2、314.5),后三个(221.6、245.2、299.2),后三个(167.7、221.6、245.2)的最小值,依此类推,直到前三个(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. 在第2行。
Since sets are unordered, you should make a
a list instead, which is an ordered data structure: 由于集合是无序的,因此您应该创建a
列表,这是一个有序的数据结构:
>>> 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: 然后,您可以将列表分成3组,并为每组获取最小值:
>>> [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: 基于@RoadRunner的答案:
You want a moving minimum of 3 consecutive numbers... 您想要移动至少3个连续数字...
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. 使用-2
,可确保始终有3个数字。
Start off using a Pandas DataFrame. 从使用Pandas DataFrame开始。 One of the operations in a DataFrame is the idea of "rolling" (taking X at a time and doing something with it) DataFrame中的一项操作是“滚动”的想法(一次获取X并对其进行处理)
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) 如果您想从头开始,只需反转列表即可(我知道您那里有一个set(),但这并不是一个好的数据结构)
This is one way using bottleneck.move_min
: 这是使用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 . bottleneck
算法基于Richard Harter的滑动窗口算法的O( n ) 最小值 。 An O(1) algorithm is also available . 还可以使用 O(1)算法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.