简体   繁体   English

如果列表包含浮点数,如何在列表中选择相同的值

[英]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.

相关问题 如何从列表中选择数字序列? - How to pick a sequence of numbers from a list? 如何从具有特定阈值的列表(包含1到n个值)中选择随机否? - How to pick a random no from a list (contain 1 to n values) with certain thresold value? 在遍历包含嵌套字典和列表的字典列表时,如何选择特定值? - How do I pick specific values as I iterate through a list of dictionaries that contain nested dictionaries and lists? 如何在python的列表中添加浮点数? - How to add the floating numbers in a list in python? 如何在元组列表中选择具有特定值的元素 - How to pick elements with certain values in list of tuples 在列表中同一行上的python中格式化浮点数 - formatting floating point numbers in python on the same line from a list 计算列表中的连续数字并从另一个列表中选择相同索引处的相应数字 - Counting consecutive numbers in a list and pick corresponding numbers at the same index from another list 转换包含unicode值和浮点数的python列表 - Convert a python list having a mix of unicode values and floating numbers 如何设置新值以列出相同的数字多次出现? - How to set new values to list, with same numbers occurring multiple times? 如何从具有嵌套列表作为元素的列表中选择 n 个最小的数字 - How to pick n smallest numbers from a list with nested lists as elements
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM