[英]How to check specific numbers in list and then count specific elements till that number?
[英]Count similiar elements in a list of numbers
在 for 循環的每個迭代步驟中,我計算一個數組,看起來像
test = array([-0.23401695, -0.3880519 , -0.38805333, -0.38755048, -0.20781614,
-0.70836718, -0.38785778, -0.2346411 , -0.38757777, -0.38597846,
0.74324752, -0.38802888, -0.38768468, 0.25609106, -0.38759492,
-0.38601501, 0.12539226, -0.38780387, 0.53026535, -0.38773322,
-0.16896715, -0.54030724, -0.2340172 , 0.74325264, 0.47274894,
-0.38797809, -0.38803523, -0.2237936 , 0.85406766, -0.23401624,
-0.38803279, -0.38800347, -0.38793145, -0.38761207, -0.38795527,
-0.62081793, -0.38803845, -0.21677125, -0.38799521, 0.868606 ,
-0.3880574 , -0.38598402, 0.74379804, -0.38792198, -0.2026838 ,
-0.38805706, -0.38600679, -0.02927724, 0.46588779, -0.20076108])
我想確定數組測試中相似的元素數量,例如看起來與 -0.38 相似的元素數量.....
我嘗試了一些東西
for i in test:
counter = 0
for j in test:
if abs(i - j) < 10**(-2):
counter += 1
if counter > 20:
elements = counter - 1 # -1 for the case i=j
break
elements # --> 25
這在假設下有效,即我可以估計相似元素的數量(如果計數器 > 20)。
有人知道如何概括這一點嗎(沒有技巧 _ if counter > 20 _ 這不適用於所有情況)。
如果我正確理解了這個問題,您可以使用collections.Counter
和np.ndarray.round()
獲得相似元素的數量:
>>> test = np.array(...)
>>> Counter(test.round(2))
Counter({-0.23: 4,
-0.39: 26,
-0.21: 1,
-0.71: 1,
0.74: 3,
0.26: 1,
0.13: 1,
0.53: 1,
-0.17: 1,
-0.54: 1,
0.47: 2,
-0.22: 2,
0.85: 1,
-0.62: 1,
0.87: 1,
-0.2: 2,
-0.03: 1})
>>> len(Counter(test.round(2))) # Number of different elements
17
>>> Counter(test.round(2)).most_common()[0] # Get the most frequent item (thx @Mike Müller)
(-0.39, 26)
不要檢查counter > 20
,只返回基於 counter 的元素。
for i in test:
counter = 0
for j in test:
if abs(i - j) < 10**(-2):
counter += 1
elements = counter - 1
break
或者
以 counter = -1 開始,只返回 counter/or elemetns
for i in test:
counter = -1
for j in test:
if abs(i - j) < 10**(-2):
counter += 1
elements = counter
break
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.