Python程序返回在指定索引处具有元素的行
给定两个矩阵,任务是编写一个Python程序,该程序可以从两个矩阵中提取在第 K 个索引处具有相似元素并映射到相似行位置的所有行。
例子:
Input : test_list1 = [[1, 8, 3], [9, 2, 0], [6, 4, 4], [6, 4, 4]], test_list2 = [[1, 9, 3], [8, 2, 3], [5, 4, 6], [5, 4, 6]], K = 1
Output : [[9, 2, 0], [8, 2, 3], [6, 4, 4], [5, 4, 6], [6, 4, 4], [5, 4, 6]]
Explanation : All elements with similar elements at 1st index extracted.
Input : test_list1 = [[1, 8, 3], [9, 2, 0], [6, 4, 4], [6, 5, 4]], test_list2 = [[1, 9, 3], [8, 2, 3], [5, 4, 6], [5, 4, 6]], K = 1
Output : [[9, 2, 0], [8, 2, 3], [6, 4, 4], [5, 4, 6]]
Explanation : All elements with similar elements at 1st index extracted.
方法 1:使用循环和enumerate()
在这种情况下,列表从开始行到结束进行迭代,并匹配每行的第 K 个索引,如果找到,则将两行附加到结果中。
例子:
Python3
# initializing lists
test_list1 = [[1, 8, 3], [9, 2, 0], [6, 4, 4], [6, 4, 4]]
test_list2 = [[1, 9, 3], [8, 2, 3], [5, 4, 6], [5, 4, 6]]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# initializing K
K = 1
res = []
for idx in range(len(test_list1)):
# comparing lists
if test_list1[idx][K] == test_list2[idx][K]:
res.append(test_list1[idx])
res.append(test_list2[idx])
# printing result
print("K index matching rows : " + str(res))
Python3
# initializing lists
test_list1 = [[1, 8, 3], [9, 2, 0], [6, 4, 4], [6, 4, 4]]
test_list2 = [[1, 9, 3], [8, 2, 3], [5, 4, 6], [5, 4, 6]]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# initializing K
K = 1
# zip() combines elements together
res = []
[res.extend([t1, t2])
for t1, t2 in zip(test_list1, test_list2) if t1[K] == t2[K]]
# printing result
print("K index matching rows : " + str(res))
输出:
The original list 1 is : [[1, 8, 3], [9, 2, 0], [6, 4, 4], [6, 4, 4]]
The original list 2 is : [[1, 9, 3], [8, 2, 3], [5, 4, 6], [5, 4, 6]]
K index matching rows : [[9, 2, 0], [8, 2, 3], [6, 4, 4], [5, 4, 6], [6, 4, 4], [5, 4, 6]]
方法 2:使用列表推导和zip()
在此,我们使用 zip() 执行获取配对的任务,然后比较第 K 个元素,使用 extend() 和列表推导进行追加和迭代。
例子:
蟒蛇3
# initializing lists
test_list1 = [[1, 8, 3], [9, 2, 0], [6, 4, 4], [6, 4, 4]]
test_list2 = [[1, 9, 3], [8, 2, 3], [5, 4, 6], [5, 4, 6]]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# initializing K
K = 1
# zip() combines elements together
res = []
[res.extend([t1, t2])
for t1, t2 in zip(test_list1, test_list2) if t1[K] == t2[K]]
# printing result
print("K index matching rows : " + str(res))
输出:
The original list 1 is : [[1, 8, 3], [9, 2, 0], [6, 4, 4], [6, 4, 4]]
The original list 2 is : [[1, 9, 3], [8, 2, 3], [5, 4, 6], [5, 4, 6]]
K index matching rows : [[9, 2, 0], [8, 2, 3], [6, 4, 4], [5, 4, 6], [6, 4, 4], [5, 4, 6]]