Warm tip: This article is reproduced from serverfault.com, please click

Removing Items From List while iterating with For loop

发布于 2020-11-27 23:48:59

I am pulling values from my database and my variables in my list are in this form:

my_list = [<task1>, <task2>, <task3>]

I want to add them to a new variable:

new_list = []

When I do:

for x in my_list:
    print(x.task_urgency)

I get the value from all three rows, of the column value 'task_urgency'

for x in my_list:
    if x.task_urgency == "New!":
        my_list.remove(x)
        new_list.append(x)

When I iterate through, it doesn't find and delete all the values because of the way the indexing system works with removing values while in a for loop, but I need it to delete the certain ' for that value of x...

I am new to the values that are contained in <> and not sure how i can accomplish this.

Questioner
TheAdmin
Viewed
0
TheAdmin 2020-11-28 09:49:32

Solution:

my_list = []
new_list = []
count = 0
for y in my_list:
    if y == "New!":
        count += 1
While True:
    if count > 0: 
        for x in my_list:
            if x.task_urgency == "New!":
                my_list.remove(x)
                new_list.append(x)
                break
     else:
         break