如何将每日价格与最近5天进行比较?

时间:2019-04-01 19:16:29

标签: python list indexing

我想确定每日价格是否大于最近5天的最后一天。 我是编程新手。但是,即使我知道这也是编写大量代码的方式。

DAILY_PRICE = [ 1,2,3,6,5,6,7,8,5,6,7,6,7,5] 
COMMENT =  IN REALITY DAILY_PRICE LIST IS FULL OF STOCK PRICES

PRICE = DAILY_PRICE[-1]
PRICE1 = DAILY_PRICE[-2]
PRICE2 = DAILY_PRICE[-3]
PRICE3 = DAILY_PRICE[-4]
PRICE4 = DAILY_PRICE[-5]
PRICE5 = DAILY_PRICE[-6]

if PRICE > PRICE1:
    print("YES")
else:
    print("NO")

if PRICE > PRICE1 and PRICE > PRICE2:
    print("YES")
else:
    print("NO")
if PRICE > PRICE1 and PRICE > PRICE2 and PRICE > PRICE3:
    print("YES")
else:
    print("NO")
if PRICE > PRICE1 and PRICE > PRICE2 and PRICE > PRICE3 and  PRICE >  PRICE4:
    print("YES")
else:
    print("NO")


if PRICE > PRICE1 and PRICE > PRICE2 and PRICE > PRICE3 and PRICE >   PRICE4 and PRICE > PRICE5:
    print("YES")
else:
    print("NO")

COMMENT = THE PRINTS IS ONLY THERE FOR CONFIRMATION, LATER I WILL STORE THE TRUE OR FALSE VALUES IN OTHER VARIABLES

2 个答案:

答案 0 :(得分:1)

使用all

DAILY_PRICE = [ 1,2,3,6,5,6,7,8,5,6,7,6,7,5] 

greater_than_last_5 = all(DAILY_PRICE[-1] > price for price in DAILY_PRICE[-6:-1])

print(greater_than_last_5)
# False

答案 1 :(得分:0)

使用列表切片,enumerate()all()在包含当前索引的5个索引的数据切片上进行检查:

此代码将在整个数据列表上提供为期5天的滑动窗口的输出:

DAILY_PRICE =  [ 1,2,3,6,5,6,7,8,5,6,7,6,7,5]  
#                          ^ window starts here, before it is less then 5 days of data


for index,price in enumerate(DAILY_PRICE):
    if index < 5 :
        continue # no comparison for first 5 prices

    if all(p <= price for p in DAILY_PRICE[index-5:index]):
        print(f"All prices {DAILY_PRICE[index-5:index]} lower/equal then {price}")
    else:
        print(f"Not all prices {DAILY_PRICE[index-5:index]} lower/equal then {price}")

输出:

All prices [1, 2, 3, 6, 5] lower/equal then 6
All prices [2, 3, 6, 5, 6] lower/equal then 7
All prices [3, 6, 5, 6, 7] lower/equal then 8
Not all prices [6, 5, 6, 7, 8] lower/equal then 5
Not all prices [5, 6, 7, 8, 5] lower/equal then 6
Not all prices [6, 7, 8, 5, 6] lower/equal then 7
Not all prices [7, 8, 5, 6, 7] lower/equal then 6
Not all prices [8, 5, 6, 7, 6] lower/equal then 7
Not all prices [5, 6, 7, 6, 7] lower/equal then 5   # this is the one your code tries to do
                                                    # all(p <= DAILY_PRICE[-1] for p 
                                                    #                in DAILY_PRICE[-6:-1])