Python - 提取成对的行
给定一个矩阵,任务是编写一个Python程序来提取所有具有成对元素的行。即元素的频率为 mod 2。
Input : test_list = [[10, 2, 3, 2, 3], [5, 5, 4, 7, 7, 4], [1, 2], [1, 1, 2, 2]]
Output : [[5, 5, 4, 7, 7, 4], [1, 1, 2, 2]]
Explanation : All rows have pair elements, i.e have even occurrence.
Input : test_list = [[10, 2, 3, 2, 3], [5, 5, 4, 7, 4], [1, 2], [1, 1, 2, 2]]
Output : [[1, 1, 2, 2]]
Explanation : All rows have pair elements, i.e have even occurrence.
方法 #1:使用all() +列表推导+ count()
在这里,我们使用count()检查每个元素的计数, all()用于测试所有元素的频率是否可以被 2 整除。
Python3
# Python3 code to demonstrate working of
# Extract Paired Rows
# Using all() + list comprehension + count()
# initializing list
test_list = [[10, 2, 3, 2, 3], [5, 5, 4, 7, 7, 4],
[1, 2], [1, 1, 2, 2]]
# printing original list
print("The original list is : " + str(test_list))
# count() checks for frequency to be mod 2
res = [row for row in test_list if all(
row.count(ele) % 2 == 0 for ele in row)]
# printing result
print("Extracted rows : " + str(res))
Python3
# Python3 code to demonstrate working of
# Extract Paired Rows
# Using filter() + lambda + count() + all()
# initializing list
test_list = [[10, 2, 3, 2, 3], [5, 5, 4, 7, 7, 4],
[1, 2], [1, 1, 2, 2]]
# printing original list
print("The original list is : " + str(test_list))
# count() checks for frequency to be mod 2
# filter() and lambda used to perform filtering
res = list(filter(lambda row: all(
row.count(ele) % 2 == 0 for ele in row), test_list))
# printing result
print("Extracted rows : " + str(res))
输出:
The original list is : [[10, 2, 3, 2, 3], [5, 5, 4, 7, 7, 4], [1, 2], [1, 1, 2, 2]]
Extracted rows : [[5, 5, 4, 7, 7, 4], [1, 1, 2, 2]]
方法#2:使用filter() + lambda + count() + all()
在这里,我们使用filter()和lambda函数而不是列表推导来执行过滤任务。 count()和all()用于检查行中所有元素的频率。
蟒蛇3
# Python3 code to demonstrate working of
# Extract Paired Rows
# Using filter() + lambda + count() + all()
# initializing list
test_list = [[10, 2, 3, 2, 3], [5, 5, 4, 7, 7, 4],
[1, 2], [1, 1, 2, 2]]
# printing original list
print("The original list is : " + str(test_list))
# count() checks for frequency to be mod 2
# filter() and lambda used to perform filtering
res = list(filter(lambda row: all(
row.count(ele) % 2 == 0 for ele in row), test_list))
# printing result
print("Extracted rows : " + str(res))
输出:
The original list is : [[10, 2, 3, 2, 3], [5, 5, 4, 7, 7, 4], [1, 2], [1, 1, 2, 2]]
Extracted rows : [[5, 5, 4, 7, 7, 4], [1, 1, 2, 2]]