为列表获取更高的粒度,同时为每个新点将另一个列表中的相应元素设置为 0

Get higher granularity for a list while setting 0 to the corresponding element in the other list for each new point

我有两个相同大小的列表,比方说:

A = [100.44 , 101.05, 103.25, 103.78] # product price
B = [     20,     20,     50,     50] # quantity for the above product price (20 refers to price 100, etc)

我希望能够构建两个新列表,对于给定的新粒度,例如 0.2:

A = [100.44, 100.64, 100.84, 101.04, 101.05, 101.25, etc] # higher granularity for list A
B = [    20,      0,      0,      0,     20,     0,  etc] # for each new element in list A, corresponding value in B should be set to 0

备注:所有数字都是'float'类型,我想要的更高粒度可以是任何东西,例如(0.1,0.12等)。

感谢您的帮助!

一种方法:

def increase_granularity(A, B, size=0.2, rounding_digits=2):
    # create a dictionary that maps price to quantity
    input_dict = dict(zip(A,B))
    new_A, new_B = [], []
    # iteratively add size to price values to increase granularity between any consecutive prices
    for a_min, a_max in zip(A, A[1:]):
        while a_min < a_max:
            new_A.append(round(a_min, rounding_digits))
            # get the quantity that corresponds to a price if it exists; 0 otherwise
            new_B.append((input_dict.get(a_min, 0)))
            a_min += size
    since `zip` does not read the last item in `A`, append it manually
    new_A.append(A[-1])
    new_B.append(B[-1])
    return new_A, new_B

new_A, new_B = increase_granularity(A, B, 0.2)

输出:

>>>print(new_A)
[100.44, 100.64, 100.84, 101.04, 101.05, 101.25, 101.45, 101.65, 101.85, 102.05, 
 102.25, 102.45, 102.65, 102.85, 103.05, 103.25, 103.45, 103.65, 103.78]

>>>print(new_B)
[20, 0, 0, 0, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 50, 0, 0, 50]

编辑: 由于问题被编辑为列表仅包含浮点值,因此先前的答案将永远无效。这是我编辑过的答案。这可能不是一个完美的解决方案,但您可以尝试作为替代方案。

import numpy as np

A = [100.44 , 101.05, 103.25, 105.78] #Modified the list with float values
B = [20, 20, 5, 50 ]

arr = np.array(A) // 1 #just for comparing with a rounded(1) array.

sequences = np.arange(min(A), max(A)) // 1 # Rounding to 1 since we need only that value to be compared
sequences = sequences.tolist() # Converting to list so that we can get the index of the element

# Now we need to find out the indices of newly added prices in the sequences array.
indices = [sequences.index(p) for p in sequences if not p in arr]

[B.insert(i, 0)  for i in indices] 
print(B)

输出:

[20, 20, 0, 5, 0, 50]