Python - 过滤排序的行
给定一个矩阵,提取按升序或降序排序的行。
Input : test_list = [[3, 6, 8, 10], [1, 8, 2, 4, 3], [8, 5, 3, 2], [1, 4, 5, 3]]
Output : [[3, 6, 8, 10], [8, 5, 3, 2]]
Explanation : Both lists are ordered, 1st ascending, second descending.
Input : test_list = [[3, 6, 8, 10], [1, 8, 2, 4, 3], [8, 5, 7, 2], [1, 4, 5, 3]]
Output : [[3, 6, 8, 10]]
Explanation : List ordered in ascending order.
方法 #1:使用列表理解+ sorted() + reverse
在这里,我们检查每一行,通过 sorted() 执行排序,并通过将 reverse 作为关键字进行反向排序。
Python3
# Python3 code to demonstrate working of
# Filter Sorted Rows
# Using list comprehension + sorted() + reverse
# initializing list
test_list = [[3, 6, 8, 10], [1, 8, 2, 4, 3], [8, 5, 3, 2], [1, 4, 5, 3]]
# printing original list
print("The original list is : " + str(test_list))
# filtering using sorted() and reverse as key
res = [sub for sub in test_list if sub == list(
sorted(sub)) or sub == list(sorted(sub, reverse=True))]
# printing result
print("Extracted rows : " + str(res))
Python3
# Python3 code to demonstrate working of
# Filter Sorted Rows
# Using filter() + lambda + sorted() + reverse
# initializing list
test_list = [[3, 6, 8, 10], [1, 8, 2, 4, 3], [8, 5, 3, 2], [1, 4, 5, 3]]
# printing original list
print("The original list is : " + str(test_list))
# filtering using sorted() and reverse as key
res = list(filter(lambda sub: sub == list(sorted(sub)) or sub ==
list(sorted(sub, reverse=True)), test_list))
# printing result
print("Extracted rows : " + str(res))
输出:
The original list is : [[3, 6, 8, 10], [1, 8, 2, 4, 3], [8, 5, 3, 2], [1, 4, 5, 3]]
Extracted rows : [[3, 6, 8, 10], [8, 5, 3, 2]]
方法#2:使用filter() + lambda + sorted() + reverse
在这里,我们使用 lambda 和 sorted() 执行过滤任务,而 reverse 可用于检查与有序列表的相等性。
蟒蛇3
# Python3 code to demonstrate working of
# Filter Sorted Rows
# Using filter() + lambda + sorted() + reverse
# initializing list
test_list = [[3, 6, 8, 10], [1, 8, 2, 4, 3], [8, 5, 3, 2], [1, 4, 5, 3]]
# printing original list
print("The original list is : " + str(test_list))
# filtering using sorted() and reverse as key
res = list(filter(lambda sub: sub == list(sorted(sub)) or sub ==
list(sorted(sub, reverse=True)), test_list))
# printing result
print("Extracted rows : " + str(res))
输出:
The original list is : [[3, 6, 8, 10], [1, 8, 2, 4, 3], [8, 5, 3, 2], [1, 4, 5, 3]]
Extracted rows : [[3, 6, 8, 10], [8, 5, 3, 2]]