【问题标题】:Count similiar elements in a list of numbers计算数字列表中的相似元素
【发布时间】:2020-05-29 08:59:02
【问题描述】:

在 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 _ 这不适用于所有情况)。

【问题讨论】:

  • 两个数之间相似度的条件是什么?
  • 如果条件 abs(i - j)

标签: python list numpy for-loop counter


【解决方案1】:

如果我对问题的理解正确,您可以使用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(test.round(2)).most_common()[0]
  • @MikeMüller 不知道这种方法 - 谢谢 :)
【解决方案2】:

不检查counter &gt; 20,只根据计数器返回元素。

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/或 elemetns

for i in test:
        counter = -1

        for j in test:
            if abs(i - j) < 10**(-2):
                counter += 1

            elements = counter
            break

【讨论】:

    猜你喜欢
    • 2014-05-14
    • 2017-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多