Python程序按自定义元素计数对矩阵的行进行排序
给定 Matrix,以下程序显示如何根据指定列表中数字的出现次数对矩阵的行进行排序。
Input : test_list = [[4, 5, 1, 7], [6, 5], [9, 8, 2], [7, 1]], cus_list = [4, 5, 7]
Output : [[9, 8, 2], [6, 5], [7, 1], [4, 5, 1, 7]]
Explanation : 0 < 1 = 1 < 3 is order of custom elements count.
Input : test_list = [[4, 5, 1, 7], [6, 5], [7, 1]], cus_list = [4, 5, 7]
Output : [[6, 5], [7, 1], [4, 5, 1, 7]]
Explanation : 1 = 1 < 3 is order of custom elements count.
方法 1:使用sort()和len()
在此,我们使用 sort() 执行就地排序,并检查所有元素并在自定义列表中存在元素的情况下增加计数器,len() 返回长度以获取计数。
Python3
# sorting util.
def get_count(sub):
return len([ele for ele in sub if ele in cus_list])
# initializing list
test_list = [[4, 5, 1, 7], [6, 5], [9, 8, 2], [7, 1]]
# printing original list
print("The original list is : " + str(test_list))
# initializing custom list
cus_list = [4, 5, 7]
# performing inplace sort
test_list.sort(key=get_count)
# printing result
print("Sorted Matrix : " + str(test_list))
Python3
# initializing list
test_list = [[4, 5, 1, 7], [6, 5], [9, 8, 2], [7, 1]]
# printing original list
print("The original list is : " + str(test_list))
# initializing custom list
cus_list = [4, 5, 7]
# performing sort using sorted()
res = sorted(test_list, key=lambda sub: len(
[ele for ele in sub if ele in cus_list]))
# printing result
print("Sorted Matrix : " + str(res))
输出:
The original list is : [[4, 5, 1, 7], [6, 5], [9, 8, 2], [7, 1]]
Sorted Matrix : [[9, 8, 2], [6, 5], [7, 1], [4, 5, 1, 7]]
方法 2:使用sorted() 、 lambda和len()
解决此问题的另一种方法是使用 sorted() 执行排序任务,并且 lambda函数提供一个语句逻辑,而无需调用外部函数。
蟒蛇3
# initializing list
test_list = [[4, 5, 1, 7], [6, 5], [9, 8, 2], [7, 1]]
# printing original list
print("The original list is : " + str(test_list))
# initializing custom list
cus_list = [4, 5, 7]
# performing sort using sorted()
res = sorted(test_list, key=lambda sub: len(
[ele for ele in sub if ele in cus_list]))
# printing result
print("Sorted Matrix : " + str(res))
输出:
The original list is : [[4, 5, 1, 7], [6, 5], [9, 8, 2], [7, 1]]
Sorted Matrix : [[9, 8, 2], [6, 5], [7, 1], [4, 5, 1, 7]]