我有兩個相同大小的串列,比如說:
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
備注:所有數字都是“浮點”型別,我想要的更高粒度可以是任何東西,例如(0.1、0.12 等)。
謝謝您的幫助 !
uj5u.com熱心網友回復:
編輯: 由于問題被編輯為串列僅包含浮點值,因此之前的答案將永遠不會起作用。這是我編輯的答案。這可能不是一個完美的解決方案,但您可以嘗試作為替代方案。
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]
uj5u.com熱心網友回復:
一種方法:
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]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/413341.html
標籤:
