![](/img/trans.png)
[英]How can I pull one item, from a list of dictionary items, using a single key:value pair?
[英]How can I select single item from one list and doing operation on all items of second list using Python
例如,如果我有一個包含data的列表,並且應該逐項選擇其項
a = [0.11 , 0.22 , 0.13, 6.7, 2.5, 2.8]
另一個應選擇所有項目
b = [1.2 1.4, 2.6, 2.3, 5.7 9.9]
如果我從a中選擇0.11
並對b的所有項目進行加法運算,然后將結果保存到新數組或list中,那么使用python怎么可能呢? ...
對於這個問題,我感到很抱歉,因為我想自己學習python,請告訴我這是怎么可能的。
先感謝您。
您需要一個嵌套循環 。 您可以通過列表理解來生成列表列表:
[[item_a + item_b for item_b in b] for item_a in a]
如果您希望最終結果是列表列表,則可以這樣:
c = [[x + y for x in b] for y in a]
如果您希望最終結果是一個列表,而下一個子列表彼此附加,則可以這樣編寫:
c=[]
for (y in a):
c += ([y + x for x in b])
另一個選擇是將列表轉換為numpy數組,然后利用numpy數組的broadcast屬性:
import numpy as np
npA = np.array(a)
npB = np.array(b)
npA[:, None] + npB
array([[ 1.31, 1.51, 2.71, 2.41, 5.81, 10.01],
[ 1.42, 1.62, 2.82, 2.52, 5.92, 10.12],
[ 1.33, 1.53, 2.73, 2.43, 5.83, 10.03],
[ 7.9 , 8.1 , 9.3 , 9. , 12.4 , 16.6 ],
[ 3.7 , 3.9 , 5.1 , 4.8 , 8.2 , 12.4 ],
[ 4. , 4.2 , 5.4 , 5.1 , 8.5 , 12.7 ]])
您還可以使用以下方法簡單地執行元素明智的乘法:
npA[:, None] * npB
返回:
array([[ 0.132, 0.154, 0.286, 0.253, 0.627, 1.089],
[ 0.264, 0.308, 0.572, 0.506, 1.254, 2.178],
[ 0.156, 0.182, 0.338, 0.299, 0.741, 1.287],
[ 8.04 , 9.38 , 17.42 , 15.41 , 38.19 , 66.33 ],
[ 3. , 3.5 , 6.5 , 5.75 , 14.25 , 24.75 ],
[ 3.36 , 3.92 , 7.28 , 6.44 , 15.96 , 27.72 ]])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.