慕蓋茨4494581
2023-06-06 10:38:50
這是我問過的關(guān)于根據(jù)條件按元素填充新列表的上一個問題的后續(xù)問題。我現(xiàn)在想知道我是否可以創(chuàng)建第二個新列表,該列表仍然有條件地填充在第一個列表理解中。最初我有:?old_list1 = np.reshape(old_data, (49210, 1)) #Reshape into 1D array?new_list1 = [None] #Create empty list to be filled?max_value = np.nanmax(old_list1)?threshold = 0.75 * max_value #Create threshold to be used as condition for new list....然后,根據(jù)我對上一個問題的回答,我可以根據(jù)threshold以下內(nèi)容創(chuàng)建一個新列表:new_list1 = [element[0] for element in old_list1 if element[0] > threshold]我有另一個列表 ,old_list2其長度與 相同old_list1。我可以使用仍然以滿足條件new_list2的匹配元素為條件的列表理解來創(chuàng)建嗎?old_list1threshold也就是說,是這樣的:j = 0for i in range(len(old_list1)):? ? if old_list1[i] > threshold:? ? ? ? ?new_list1[j] = old_list[i]? ? ? ? ?new_list2[j] = old_list2[i]? ? ? ? ?j += 1?...可能與列表理解?一如既往地謝謝你!
1 回答

繁星coding
TA貢獻(xiàn)1797條經(jīng)驗(yàn) 獲得超4個贊
是的你可以。您可以結(jié)合使用列表理解來zip關(guān)聯(lián)項(xiàng)目?;蛘撸绻呀?jīng)擁有數(shù)組中的數(shù)據(jù)numpy,只需使用條件索引:
import numpy as np
data1 = np.array([10, 1, 9, 8])
threshold = 0.75 * np.nanmax(data1) # 7.5 in this example
data2 = np.array([500, 200, 300, 100])
# using list comprehension and zip
new_data = [t[1] for t in zip(data1, data2) if t[0] > threshold]
print(new_data) # [500, 300, 100]
# using numpy's conditional indexing...
new_data2 = data2[data1 > threshold]
print(new_data2) # [500 300 100]
添加回答
舉報(bào)
0/150
提交
取消