Python - 按 K 倍数对行进行排序
给定一个矩阵,按行中存在的 K 的倍数执行行排序。
Input : test_list = [[3, 4, 8, 1], [12, 32, 4, 16], [1, 2, 3, 4], [9, 7, 5]], K = 4
Output : [[9, 7, 5], [1, 2, 3, 4], [3, 4, 8, 1], [12, 32, 4, 16]]
Explanation : 0 < 1 < 2 < 4, multiple of 4 occurrence order.
Input : test_list = [[3, 4, 8, 1], [12, 32, 4, 16], [1, 2, 3, 4], [9, 7, 5]], K = 2
Output : [[9, 7, 5], [1, 2, 3, 4], [3, 4, 8, 1], [12, 32, 4, 16]]
Explanation : 0 < 2 = 2 < 4, multiple of 2 occurrence order.
方法 #1:使用 sort() + %运算符+ len()
在此,我们使用 %运算符测试多个,然后通过获取过滤元素的长度来计算计数,提供给 sort() 执行行的就地排序的键。
Python3
# Python3 code to demonstrate working of
# Sort row by K multiples
# Using sort() + % operator + len()
# checking for multiples count
def k_mul(row):
return len([ele for ele in row if ele % K == 0])
# initializing list
test_list = [[3, 4, 8, 1], [12, 32, 4, 16], [1, 2, 3, 4], [9, 7, 5]]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 4
# performing sort
test_list.sort(key=k_mul)
# printing result
print("Sorted result : " + str(test_list))
Python3
# Python3 code to demonstrate working of
# Sort row by K multiples
# Using sorted() + lambda + len()
# initializing list
test_list = [[3, 4, 8, 1], [12, 32, 4, 16], [1, 2, 3, 4], [9, 7, 5]]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 4
# performing sort using sorted()
# lambda avoiding external function call
res = sorted(test_list, key=lambda row: len(
[ele for ele in row if ele % K == 0]))
# printing result
print("Sorted result : " + str(res))
输出:
The original list is : [[3, 4, 8, 1], [12, 32, 4, 16], [1, 2, 3, 4], [9, 7, 5]]
Sorted result : [[9, 7, 5], [1, 2, 3, 4], [3, 4, 8, 1], [12, 32, 4, 16]]
方法 #2:使用sorted() + lambda + len()
在这种情况下,排序是使用 sorted() 完成的,len() 用于获取 K 的所有倍数的长度,如上述方法。 lambda函数提供单语句替代来执行逻辑注入。
蟒蛇3
# Python3 code to demonstrate working of
# Sort row by K multiples
# Using sorted() + lambda + len()
# initializing list
test_list = [[3, 4, 8, 1], [12, 32, 4, 16], [1, 2, 3, 4], [9, 7, 5]]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 4
# performing sort using sorted()
# lambda avoiding external function call
res = sorted(test_list, key=lambda row: len(
[ele for ele in row if ele % K == 0]))
# printing result
print("Sorted result : " + str(res))
输出:
The original list is : [[3, 4, 8, 1], [12, 32, 4, 16], [1, 2, 3, 4], [9, 7, 5]]
Sorted result : [[9, 7, 5], [1, 2, 3, 4], [3, 4, 8, 1], [12, 32, 4, 16]]