簡體   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