python 向量元素判断_python;计算向量的元素
你的代碼很少出錯。在my vector a should be of dimension 10, but it isn't!
這是因為你不會在列表中只添加10個元素。看看你的邏輯。在for t in range(0,10,1):
for j in range(0, len(c)):
if c[j]>t/10:
a.append(sum(c[j]>t))
對于每個閾值,t,每次迭代一個c中的所有12個項目,并向列表中追加一些內容。總的來說,你有120個項目。你應該做的是(在偽代碼中):
^{pr2}$
numpy.where()提供滿足條件的數組中的索引,因此您只需計算每次獲得的索引數。我們將得到完整的解決方案是片刻。在
另一個潛在的錯誤是t/10,在python2中是整數除法,對于所有閾值都將返回0。正確的方法是使用t/10.強制浮點除法。如果您使用的是python3,那么默認情況下會得到浮點除法,所以這可能不是問題。請注意,您做了c[j] > t,其中t介于0和10之間。總的來說,你的c[j] > t邏輯是錯誤的。你想對所有的元素使用一個計數器,就像其他答案告訴你的那樣,或者把它全部分解成一行行的列表理解。在
最后,這里有一個充分利用numpy的解決方案。在import numpy as np
c = np.array([0.3, 0.2, 0.3, 0.6, 0.9, 0.1, 0.2, 0.5, 0.3, 0.5, 0.7, 0.1])
thresh = np.arange(0, 1, 0.1)
counts = np.empty(thresh.shape, dtype=int)
for i, t in enumerate(thresh):
counts[i] = len(np.where(c > t)[0])
print counts
輸出:[12 10 8 5 5 3 2 1 1 0]
讓numpy處理引擎蓋下的循環比Python級別的循環更快。用于演示:import timeit
head = """
import numpy as np
c = np.array([0.3, 0.2, 0.3, 0.6, 0.9, 0.1, 0.2, 0.5, 0.3, 0.5, 0.7, 0.1])
thresh = np.arange(0, 1, 0.1)
"""
numpy_where = """
for t in thresh:
len(np.where(c > t)[0])
"""
python_loop = """
for t in thresh:
len([element for element in c if element > t])
"""
n = 10000
for test in [numpy_where, python_loop]:
print timeit.timeit(test, setup=head, number=n)
在我的電腦上會產生以下計時結果。在0.231292377372
0.321743753994
總結
以上是生活随笔為你收集整理的python 向量元素判断_python;计算向量的元素的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python qq模块_Python的n
- 下一篇: websocket python爬虫_p