Python程序按绝对差异的频率对元组进行排序
给定双元组列表,这里的任务是编写一个Python程序,可以按元素绝对差异的频率对它们进行排序。
Input : [(1, 6), (11, 3), (9, 1), (6, 11), (2, 10), (5, 7)]
Output : [(5, 7), (1, 6), (6, 11), (11, 3), (9, 1), (2, 10)]
Explanation : 7 – 5 = 2 occurs only 1 time. 5 occurs twice [( 6 – 1), (11 – 6)] and 8 occurs 3 times as difference.
Input : [(1, 6), (6, 11), (5, 7)]
Output : [(5, 7), (1, 6), (6, 11)]
Explanation : 7 – 5 = 2 occurs only 1 time. 5 occurs twice [( 6 – 1), (11 – 6)].
方法:使用sorted() 、 abs() 、 count()和列表推导式
在这里,我们使用 abs() 和列表理解来执行计算每个绝对差异的任务。然后使用 sorted() 和 count() 根据绝对差的计算结果对元组进行排序。
例子:
Python3
# initializing list
test_list = [(1, 6), (11, 3), (9, 1), (6, 11), (2, 10), (5, 7)]
# printing original list
print("The original list is : " + str(test_list))
# getting differences pairs
diff_list = [abs(x - y) for x, y in test_list]
# sorting list by computed differences
res = sorted(test_list, key = lambda sub: diff_list.count(abs(sub[0] - sub[1])))
# printing result
print("Sorted Tuples : " + str(res))
输出:
The original list is : [(1, 6), (11, 3), (9, 1), (6, 11), (2, 10), (5, 7)]
Sorted Tuples : [(5, 7), (1, 6), (6, 11), (11, 3), (9, 1), (2, 10)]