Python - 查找大于列表中每个元素的数字的频率
给定一个列表,构造一个新列表,该列表的元素频率大于或等于它,对应于列表中的每个元素。
Input : test_list = [6, 3, 7, 1, 2, 4]
Output : [2, 4, 1, 6, 5, 3]
Explanation : 6, 7 are greater or equal to 6 in list, hence 2.
Input : test_list = [6, 3, 7]
Output : [2, 3, 1]
Explanation : 6, 7 are greater or equal to 6 in list, hence 2.
方法 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))
输出:
The original list is : [6, 3, 7, 1, 2, 4]
Greater elements Frequency list : [2, 4, 1, 6, 5, 3]
方法 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))
输出:
The original list is : [6, 3, 7, 1, 2, 4]
Greater elements Frequency list : [2, 4, 1, 6, 5, 3]