Python – 从第 j 列值中提取第 i 列值
有时,在使用Python Matrix 时,我们可能会遇到需要从比较第 j 列的值中提取第 i 列值的问题。这种问题可能发生在学校编程或网络开发等领域。让我们讨论可以执行此任务的某些方式。
Input : test_list = [[4, 5, 6], [2, 5, 7], [9, 8, 2], [10, 2, 6]], search_list = [4, 9], search_idx = 0, ext_idx = 2
Output : [6, 2]
Input : test_list = [[4, 5, 6], [2, 5, 7], [9, 8, 2], [10, 2, 6]], search_list = [2, 6], search_idx = 2, ext_idx = 0
Output : [4, 9, 10]
方法#1:使用循环
这是解决这个问题的粗暴方法。在此,我们遍历每一行并将第 j 列与列表元素进行比较,如果存在,则提取第 i 个元素。
# Python3 code to demonstrate working of
# Extract ith column values from jth column values
# Using loop
# initializing list
test_list = [[4, 5, 6], [2, 5, 7], [9, 8, 2], [10, 2, 6]]
# printing original list
print("The original list is : " + str(test_list))
# initializing list
search_list = [5, 2]
# initializing search index
search_idx = 1
# initializing extract index
ext_idx = 2
# Extract ith column values from jth column values
# Using loop
res = []
for sub in test_list:
if sub[search_idx] in search_list:
res.append(sub[ext_idx])
# printing result
print("The extracted elements : " + str(res))
输出 :
The original list is : [[4, 5, 6], [2, 5, 7], [9, 8, 2], [10, 2, 6]]
The extracted elements : [6, 7, 6]
方法 #2:使用set() + list comprehension
上述功能的组合可以用来解决这个问题。在此,我们以与上述方法类似的方式执行提取元素的任务,只是使用速记。此外,为了减少初始数据搜索,搜索列表将转换为 set(),以删除重复项。
# Python3 code to demonstrate working of
# Extract ith column values from jth column values
# Using set() + list comprehension
# initializing list
test_list = [[4, 5, 6], [2, 5, 7], [9, 8, 2], [10, 2, 6]]
# printing original list
print("The original list is : " + str(test_list))
# initializing list
search_list = [5, 2]
# initializing search index
search_idx = 1
# initializing extract index
ext_idx = 2
# Extract ith column values from jth column values
# Using set() + list comprehension
temp = set(search_list)
res = [sub[ext_idx] for sub in test_list if sub[search_idx] in search_list]
# printing result
print("The extracted elements : " + str(res))
输出 :
The original list is : [[4, 5, 6], [2, 5, 7], [9, 8, 2], [10, 2, 6]]
The extracted elements : [6, 7, 6]