📜  Python - 多尺寸矩阵的后列

📅  最后修改于: 2022-05-13 01:55:14.369000             🧑  作者: Mango

Python - 多尺寸矩阵的后列

给定一个具有可变长度行的矩阵,提取最后一列。

方法#1:使用循环

这是解决这个问题的蛮力方法,我们使用“-1”访问最后一个元素,对每一行进行迭代。

Python3
# Python3 code to demonstrate working of 
# Rear column in Multisized Matrix
# Using loop
  
# initializing list
test_list = [[3, 4, 5], [7], [8, 4, 6, 1], [10, 3]]
  
# printing original list
print("The original list is : " + str(test_list))
  
res = []
for sub in test_list:
      
    # getting rear element using "-1"
    res.append(sub[-1])
  
# printing results
print("Filtered column : " + str(res))


Python3
# Python3 code to demonstrate working of 
# Rear column in Multisized Matrix
# Using list comprehension
  
# initializing list
test_list = [[3, 4, 5], [7], [8, 4, 6, 1], [10, 3]]
  
# printing original list
print("The original list is : " + str(test_list))
  
# one-liner to solve this problem
res = [sub[-1] for sub in test_list]
  
# printing results
print("Filtered column : " + str(res))


输出
The original list is : [[3, 4, 5], [7], [8, 4, 6, 1], [10, 3]]
Filtered column : [5, 7, 1, 3]

方法#2:使用列表推导

这是解决此问题的另一种方法,在此,我们以类似的方式执行上述任务,只是作为速记。

Python3

# Python3 code to demonstrate working of 
# Rear column in Multisized Matrix
# Using list comprehension
  
# initializing list
test_list = [[3, 4, 5], [7], [8, 4, 6, 1], [10, 3]]
  
# printing original list
print("The original list is : " + str(test_list))
  
# one-liner to solve this problem
res = [sub[-1] for sub in test_list]
  
# printing results
print("Filtered column : " + str(res))
输出
The original list is : [[3, 4, 5], [7], [8, 4, 6, 1], [10, 3]]
Filtered column : [5, 7, 1, 3]