Python - 极值差异最小的行
给定一个矩阵,提取极值差异最小的行。
例子:
Input : test_list = [[4, 10, 18], [5, 0], [1, 4, 6], [19, 2]]
Output : [[1, 4, 6], [5, 0]]
Explanation : 6 – 1 = 5, 5 – 0 = 5, is minimum difference between extreme values.
Input : test_list = [[4, 10, 18], [5, 0], [2, 4, 6], [19, 2]]
Output : [[2, 4, 6]]
Explanation : 6 – 2 = 4, is min diff.
方法 #1:使用列表理解+ min()
在这里,我们计算极值之间的最小差异,然后使用列表理解来获取具有极值之间的值差异的特定行。
Python3
# Python3 code to demonstrate working of
# Matrix Minimum difference in extreme values row
# Using min() + list comprehension
# initializing list
test_list = [[4, 10, 18], [5, 3, 10], [1, 4, 6], [19, 2]]
# printing original list
print("The original list is : " + str(test_list))
# getting min value
min_val = min([max(sub) - min(sub) for sub in test_list])
# using list comprehension to filter
res = [sub for sub in test_list if max(sub) - min(sub) == min_val]
# printing result
print("Rows with Minimum difference in extreme values : " + str(res))
Python3
# Python3 code to demonstrate working of
# Matrix Minimum difference in extreme values row
# Using min() + list comprehension + filter() + lambda
# initializing list
test_list = [[4, 10, 18], [5, 3, 10], [1, 4, 6], [19, 2]]
# printing original list
print("The original list is : " + str(test_list))
# getting min value
min_val = min([max(sub) - min(sub) for sub in test_list])
# using filter() + lambda to filter
res = list(filter(lambda sub : max(sub) - min(sub) == min_val, test_list))
# printing result
print("Rows with Minimum difference in extreme values : " + str(res))
输出:
The original list is : [[4, 10, 18], [5, 3, 10], [1, 4, 6], [19, 2]]
Rows with Minimum difference in extreme values : [[1, 4, 6]]
方法 #2:使用min() +列表理解+ filter() + lambda
在此,我们使用 filter() + lambda 执行与最小值进行比较的过滤任务。
蟒蛇3
# Python3 code to demonstrate working of
# Matrix Minimum difference in extreme values row
# Using min() + list comprehension + filter() + lambda
# initializing list
test_list = [[4, 10, 18], [5, 3, 10], [1, 4, 6], [19, 2]]
# printing original list
print("The original list is : " + str(test_list))
# getting min value
min_val = min([max(sub) - min(sub) for sub in test_list])
# using filter() + lambda to filter
res = list(filter(lambda sub : max(sub) - min(sub) == min_val, test_list))
# printing result
print("Rows with Minimum difference in extreme values : " + str(res))
输出:
The original list is : [[4, 10, 18], [5, 3, 10], [1, 4, 6], [19, 2]]
Rows with Minimum difference in extreme values : [[1, 4, 6]]