Python - 删除位置行
给定一个矩阵,任务是编写一个Python程序来删除具有特定位置的行。
例子:
Input: test_list = [[3, 5, 2], [1, 8, 9],
[5, 3, 1], [0, 1, 6],
[9, 4, 1], [1, 2, 10],
[0, 1, 2]]; idx_lis = [1, 2, 5]
Output: [[3, 5, 2], [0, 1, 6], [9, 4, 1], [0, 1, 2]]
Explanation: 1st, 2nd and 5th rows are removed.
Input: test_list = [[3, 5, 2], [1, 8, 9],
[5, 3, 1], [0, 1, 6],
[9, 4, 1], [1, 2, 10],
[0, 1, 2]]; idx_lis = [1, 3, 5]
Output: [[3, 5, 2], [5, 3, 1], [9, 4, 1], [0, 1, 2]]
Explanation: 1st, 3rd and 5th rows are removed.
方法 #1:使用循环+ pop() +反向迭代
在这种情况下,使用 pop() 处理删除,并且需要反向迭代以确保由于删除时的重新排列,错误的位置行不会被删除。
Python3
# Python3 code to demonstrate working of
# Remove positional rows
# Using loop + pop() + back iteration
# initializing list
test_list = [[3, 5, 2], [1, 8, 9], [5, 3, 1],
[0, 1, 6], [9, 4, 1], [1, 2, 10],
[0, 1, 2]]
# printing original list
print("The original list is: " + str(test_list))
# initializing indices
idx_lis = [1, 2, 5]
# back iteration
for idx in idx_lis[::-1]:
# pop() used for removal
test_list.pop(idx)
# printing result
print("Matrix after removal: " + str(test_list))
Python3
# Python3 code to demonstrate working of
# Remove positional rows
# Using enumerate() + list comprehension
# initializing list
test_list = [[3, 5, 2], [1, 8, 9], [5, 3, 1],
[0, 1, 6], [9, 4, 1], [1, 2, 10],
[0, 1, 2]]
# printing original list
print("The original list is: " + str(test_list))
# initializing indices
idx_lis = [1, 2, 5]
# using enumerate() to get index and value of each row
res = [sub[1] for sub in enumerate(test_list) if sub[0] not in idx_lis]
# printing result
print("Matrix after removal: " + str(res))
输出:
The original list is: [[3, 5, 2], [1, 8, 9], [5, 3, 1], [0, 1, 6], [9, 4, 1], [1, 2, 10], [0, 1, 2]]
Matrix after removal: [[3, 5, 2], [0, 1, 6], [9, 4, 1], [0, 1, 2]]
方法 #2:使用enumerate() +列表理解
在这种情况下,我们不是按索引删除行,而是执行仅添加不属于删除索引列表的行的任务。
蟒蛇3
# Python3 code to demonstrate working of
# Remove positional rows
# Using enumerate() + list comprehension
# initializing list
test_list = [[3, 5, 2], [1, 8, 9], [5, 3, 1],
[0, 1, 6], [9, 4, 1], [1, 2, 10],
[0, 1, 2]]
# printing original list
print("The original list is: " + str(test_list))
# initializing indices
idx_lis = [1, 2, 5]
# using enumerate() to get index and value of each row
res = [sub[1] for sub in enumerate(test_list) if sub[0] not in idx_lis]
# printing result
print("Matrix after removal: " + str(res))
输出:
The original list is: [[3, 5, 2], [1, 8, 9], [5, 3, 1], [0, 1, 6], [9, 4, 1], [1, 2, 10], [0, 1, 2]]
Matrix after removal: [[3, 5, 2], [0, 1, 6], [9, 4, 1], [0, 1, 2]]