Python - 元素的索引排名
给定一个元素列表,我们的任务是获取每个元素的索引等级。
Input : test_list = [3, 4, 6, 5, 3, 4, 9, 1, 2, 1, 8, 3, 2, 3, 9]
Output : [(1, 16.0), (2, 10.0), (3, 9.333333333333334), (4, 1.5), (5, 0.6), (6, 0.3333333333333333), (8, 1.25), (9, 2.2222222222222223)]
Explanation : 1 occurs in list at index 7 and 9. 9 + 7 = 16 / 1 = 16.
Input : test_list = [3, 4, 6, 5, 3, 4, 9, 1, 2, 1, 8, 3, 2, 3, 9]
Output : [(1, 16.0), (2, 10.0), (3, 9.333333333333334), (4, 1.5), (5, 0.6), (6, 0.3333333333333333), (8, 1.25), (9, 2.2222222222222223)]
Explanation : 5 occurs at index 3. 3 / 5 = 0.6.
示例:使用循环+ filter() +列表推导+ set() + sum() +循环
在这种情况下,使用 filter() 和列表理解来提取元素的索引。 set() 用于获取列表中存在的唯一数字。 sum() 用于计算所有索引的总和。
Python3
# Python3 code to demonstrate working of
# Index Ranks of Elements
# Using loop + filter() + list comprehension. + set() + sum() + loop
# initializing list
test_list = [3, 4, 6, 5, 3, 4, 9,
1, 2, 1, 8, 3, 2, 3, 9]
# printing original list
print("The original list is : " + str(test_list))
res = []
all_ele = set(test_list)
for ele in all_ele:
# getting indices of each element
indices = list(filter(lambda sub: test_list[sub] == ele, range(len(test_list))))
# index rank
idx_rank = sum(indices) / ele
res.append((ele, idx_rank))
# printing result
print("Index rank of each element : " + str(res))
输出:
The original list is : [3, 4, 6, 5, 3, 4, 9, 1, 2, 1, 8, 3, 2, 3, 9]
Index rank of each element : [(1, 16.0), (2, 10.0), (3, 9.333333333333334), (4, 1.5), (5, 0.6), (6, 0.3333333333333333), (8, 1.25), (9, 2.2222222222222223)]