Python - 按范围包含排序
给定一个范围,按给定范围内覆盖的总范围对元组 Matrix 进行排序。 [考虑完全在范围内的元组]。
Input : test_list = [[(1, 5), (6, 10), (10, 15)], [(3, 16)], [(2, 4), (6, 8), (9, 14)], [(1, 3), (9, 13)]], i, j = 2, 15
Output : [[(3, 16)], [(1, 5), (6, 10), (10, 15)], [(1, 3), (9, 13)], [(2, 4), (6, 8), (9, 14)]]
Explanation : 0 < 4 < 4 < 9, is the magnitude of range covered in tuples lists.
Input : test_list = [[(1, 5), (6, 10), (10, 15)], [(3, 16)], [(2, 4), (6, 8), (9, 14)]], i, j = 2, 15
Output : [[(3, 16)], [(1, 5), (6, 10), (10, 15)], [(2, 4), (6, 8), (9, 14)]]
Explanation : 0 < 4 < 9, is the magnitude of range covered in tuples lists.
方法 #1:使用 sort() + sum()
在这种情况下,使用 sort() 执行就地排序,并使用 sum() 和带条件的列表理解来执行给定范围内的范围求和。
Python3
# Python3 code to demonstrate working of
# Sort by range inclusion
# Using sort() + sum()
def range_sum(row):
# summing in range element
return sum([abs(sub[1] - sub[0]) for sub in row if sub[0] > i and sub[0] < j and sub[1] > i and sub[1] < j])
# initializing list
test_list = [[(1, 5), (6, 10), (10, 15)], [(3, 16)], [
(2, 4), (6, 8), (9, 14)], [(1, 3), (9, 13)]]
# printing original list
print("The original list is : " + str(test_list))
# initializing range
i, j = 2, 15
# inplace sorting using sort()
test_list.sort(key=range_sum)
# printing result
print("Sorted List : " + str(test_list))
Python3
# Python3 code to demonstrate working of
# Sort by range inclusion
# Using sorted() + lambda + sum()
# initializing list
test_list = [[(1, 5), (6, 10), (10, 15)], [(3, 16)], [
(2, 4), (6, 8), (9, 14)], [(1, 3), (9, 13)]]
# printing original list
print("The original list is : " + str(test_list))
# initializing range
i, j = 2, 15
# sorting using sorted() + lambda
res = sorted(test_list, key=lambda row: sum(
[abs(sub[1] - sub[0]) for sub in row if sub[0] > i and sub[0] < j and sub[1] > i and sub[1] < j]))
# printing result
print("Sorted List : " + str(res))
输出:
The original list is : [[(1, 5), (6, 10), (10, 15)], [(3, 16)], [(2, 4), (6, 8), (9, 14)], [(1, 3), (9, 13)]]
Sorted List : [[(3, 16)], [(1, 5), (6, 10), (10, 15)], [(1, 3), (9, 13)], [(2, 4), (6, 8), (9, 14)]]
方法 #2:使用sorted() + lambda + sum()
在这里,我们使用 sorted() 执行排序任务,使用 lambda函数执行实用程序注入,求和使用 sum() 执行。
蟒蛇3
# Python3 code to demonstrate working of
# Sort by range inclusion
# Using sorted() + lambda + sum()
# initializing list
test_list = [[(1, 5), (6, 10), (10, 15)], [(3, 16)], [
(2, 4), (6, 8), (9, 14)], [(1, 3), (9, 13)]]
# printing original list
print("The original list is : " + str(test_list))
# initializing range
i, j = 2, 15
# sorting using sorted() + lambda
res = sorted(test_list, key=lambda row: sum(
[abs(sub[1] - sub[0]) for sub in row if sub[0] > i and sub[0] < j and sub[1] > i and sub[1] < j]))
# printing result
print("Sorted List : " + str(res))
输出:
The original list is : [[(1, 5), (6, 10), (10, 15)], [(3, 16)], [(2, 4), (6, 8), (9, 14)], [(1, 3), (9, 13)]]
Sorted List : [[(3, 16)], [(1, 5), (6, 10), (10, 15)], [(1, 3), (9, 13)], [(2, 4), (6, 8), (9, 14)]]