首页 > 解决方案 > 如何从python中的二维数组中删除n个对象?

问题描述

我有一个 2d 名称和分数数组,我想删除具有最低数组分数的学生的姓名和分数,但是当我添加 2 个或更多具有最小连续数的学生时(例如 [['a',20],[ 'b',10],['c',10],['d',10],['e',10]]) 程序只删除第一个,第三个(奇数)项。帮助我为什么会发生这种情况我的代码是:

student_list = []
for i in range(int(input())):
    student_list.append([])
    student_list[i].append(input("enter name : "))
    student_list[i].append(int(input("enter score : ")))
min_score = min(student_list,key=lambda detail: detail[1])[1]
for i in student_list:
    if (i[1] == min_score):
        student_list.remove(i)
print(student_list)

标签: python

解决方案


我们可以完成这个:

student_details = [['rock', 10], ['john', 20], ['jack', 10], ['tom', 15]]

min_score = min(student_details, key=lambda detail: detail[1])[1]

student_details_with_min_score = [
    student_detail for student_detail in student_details if student_detail[1] != min_score
]

print(student_details_with_min_score)

很抱歉选择了不同的变量名称,但我认为这些名称更具可读性。


推荐阅读