python 向量元素判断_python;计算向量的元素
你的代碼很少出錯(cuò)。在my vector a should be of dimension 10, but it isn't!
這是因?yàn)槟悴粫?huì)在列表中只添加10個(gè)元素。看看你的邏輯。在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))
對(duì)于每個(gè)閾值,t,每次迭代一個(gè)c中的所有12個(gè)項(xiàng)目,并向列表中追加一些內(nèi)容。總的來(lái)說(shuō),你有120個(gè)項(xiàng)目。你應(yīng)該做的是(在偽代碼中):
^{pr2}$
numpy.where()提供滿足條件的數(shù)組中的索引,因此您只需計(jì)算每次獲得的索引數(shù)。我們將得到完整的解決方案是片刻。在
另一個(gè)潛在的錯(cuò)誤是t/10,在python2中是整數(shù)除法,對(duì)于所有閾值都將返回0。正確的方法是使用t/10.強(qiáng)制浮點(diǎn)除法。如果您使用的是python3,那么默認(rèn)情況下會(huì)得到浮點(diǎn)除法,所以這可能不是問(wèn)題。請(qǐng)注意,您做了c[j] > t,其中t介于0和10之間。總的來(lái)說(shuō),你的c[j] > t邏輯是錯(cuò)誤的。你想對(duì)所有的元素使用一個(gè)計(jì)數(shù)器,就像其他答案告訴你的那樣,或者把它全部分解成一行行的列表理解。在
最后,這里有一個(gè)充分利用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處理引擎蓋下的循環(huán)比Python級(jí)別的循環(huán)更快。用于演示: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)
在我的電腦上會(huì)產(chǎn)生以下計(jì)時(shí)結(jié)果。在0.231292377372
0.321743753994
總結(jié)
以上是生活随笔為你收集整理的python 向量元素判断_python;计算向量的元素的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: python qq模块_Python的n
- 下一篇: python语言通过字典实现映射关系_m