📌  相关文章
📜  Python - 查找大于列表中每个元素的数字的频率

📅  最后修改于: 2022-05-13 01:54:39.942000             🧑  作者: Mango

Python - 查找大于列表中每个元素的数字的频率

给定一个列表,构造一个新列表,该列表的元素频率大于或等于它,对应于列表中的每个元素。

方法 1:使用sum()列表推导

这里,嵌套列表推导用于访问列表的每个元素,而 sum() 用于获取大于或等于索引元素的元素的总和。

Python3
# initializing list
test_list = [6, 3, 7, 1, 2, 4]
  
# printing original list
print("The original list is : " + str(test_list))
  
# sum() performs counts of element which are Greater or equal to 
res = [sum(1 for ele in test_list if sub <= ele) for sub in test_list] 
      
# printing result 
print("Greater elements Frequency list : " + str(res))


Python3
# import module
import bisect
  
# initializing list
test_list = [6, 3, 7, 1, 2, 4]
  
# printing original list
print("The original list is : " + str(test_list))
  
# sorting before bisect 
temp = sorted(test_list)
  
# getting total greater elements for each element
res = [len(test_list) - bisect.bisect_left(temp, ele) for ele in test_list]
      
# printing result 
print("Greater elements Frequency list : " + str(res))



输出:

方法 2:使用sorted() bisect_left()列表推导

在这里,我们使用 bisect_left() 得到比元素小的元素。然后,从总长度中减去如此获得的数字,我们得到大于 element 的元素计数。

蟒蛇3

# import module
import bisect
  
# initializing list
test_list = [6, 3, 7, 1, 2, 4]
  
# printing original list
print("The original list is : " + str(test_list))
  
# sorting before bisect 
temp = sorted(test_list)
  
# getting total greater elements for each element
res = [len(test_list) - bisect.bisect_left(temp, ele) for ele in test_list]
      
# printing result 
print("Greater elements Frequency list : " + str(res))

输出: