首页 > 解决方案 > 查找一个元素是否在列表的其他两个元素之间?

问题描述

在我的一个程序中,我需要确定一个元素是否在其他两个元素之间才能找到价格。例如,对于屠夫,我有一份订单、数量和价格的清单。数量[5,10,15,20,25] 价格[3,2.9,2.7,2.4,2.1] 例如,如果我有 7 的新订单,我想插入数量为 5 和 10 的价格并得到2.95(3+2.9/2) 我的问题不是计算价格,而是确定一个元素是否在我的列表中的其他两个元素之间的第一步。

提前致谢。

标签: pythonlistif-statement

解决方案


我的解决方案假设数量列表始终按升序排列,并且与价目表具有相同的长度。

quantity = [5, 10, 15, 20, 25]
price = [3, 2.9, 2.7, 2.4, 2.1]

# Could be quantity or price
list_length = len(quantity)

subtotal = 0

# Number you want to check
number = 7

for x in range(list_length):
    if x+1 == list_length:
        break

    if quantity[x] <= number and number <= quantity[i+1]:
        subtotal += price[x] + price[x+1]
        break

if subtotal:
    total = 2.95 * (subtotal / 2)
else:
    # Do something
    pass


推荐阅读