繁体   English   中英

如何从python中的2d数组中删除n个对象?

[英]how to remove n object from an 2d array in python?

我有一个二维数组的名称和分数,我想删除具有最小数组分数的学生的名称和分数,但是当我添加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)

我们做得到:

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)

很抱歉选择不同的变量名,但是我认为这些名称更易读。

使用pandasnumpy可以很容易地做到这一点。

data = [['a',20],['b',10],['c',10],['d',10],['e',10]]

解决方案: pandas

import pandas as pd

df = pd.DataFrame(data, columns = ['Name', 'Score'])
df_filtered = df.loc[df.Score>df.Score.min()]
df_filtered

输出

    Name    Score
0   a       20

解决方案: numpy

import numpy as np

names, scores = list(), list()
for name, score in data:
    names.append(name)
    scores.append(score)
s = np.array(scores)
d = np.array(data)
d[s>s.min(),:].tolist()

输出量

[['a', '20']]

在迭代列表时修改列表绝不是一个好主意。 我们在您的循环中添加一些注释,这表明:

for i in student_list:
  print("Student: {}".format(i))
  if (i[1] == min_score):
    print("Removing student: {}".format(i))
    student_list.remove(i)

# Output

Student: ['a', 20]
Student: ['b', 10]
Removing student: ['b', 10]
Student: ['d', 10]
Removing student: ['d', 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]

cleaned_student_list = [
  student
  for student in student_list
  if student[1] != min_score
]

print(cleaned_student_list)

只需创建数组的新列表,然后进行迭代

for i in list(student_list):
    if (i[1] == min_score):
        student_list.remove(i)

实际上,您是通过删除项目来迭代和更新相同的列表。 这里发生的是python评估要迭代的列表的长度。 因此,在这里您继续删除它们,将列表缩短1。然后,移至下一个索引。 希望能有所帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM