[英]How to pick same values in a list if the list contain floating numbers
In the following code I want to check how many unique values are in the list and this can be done in for loop.在下面的代码中,我想检查列表中有多少唯一值,这可以在 for 循环中完成。 After knowing the number of unique values I want to see how many times a single unique values appear in a and then I want to count their number.
知道唯一值的数量后,我想查看单个唯一值在 a 中出现的次数,然后我想计算它们的数量。 Can someone please guide me how to do that.
有人可以指导我如何做到这一点。 List contains floating points.
列表包含浮点数。 What if I convert it in numpy array and then find same values.
如果我将它转换为 numpy 数组然后找到相同的值怎么办。
`a= [1.0, 1.0, 1.0, 1.0, 1.5, 1.5, 1.5, 3.0, 3.0]
list = []
for i in a:
if i not in list:
list.append(i)
print(list)
for j in range(len(list))
g= np.argwhere(a==list[j])
print(g)`
You can use np.unique to get it done你可以使用 np.unique 来完成它
np.unique(np.array(a),return_counts=True)
You can also do it using counters from collections您也可以使用集合中的计数器来完成
from collections import Counter
Var=dict(Counter(a))
print(Var)
The primitive way is to use loops最原始的方法是使用循环
[[x,a.count(x)] for x in set(a)]
If you are not familiar with list comprehensions, this is its explaination如果你不熟悉列表推导式,这是它的解释
ls=[]
for x in set(a):
ls.append([x,a.count(x)])
print(ls)
If you want it using if else,如果你想使用 if else,
counter = dict()
for k in a:
if not k in counter:
counter[k] = 1
else:
counter[k] += 1
print(counter)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.