简体   繁体   中英

For loop is not iterating through all of the items in a list

I am currently creating a python script for a coding puzzle (advent of code) and the goal of the puzzle is to remove numbers from a list that meet certain criteria. The problem is my for loop only iterates through 3 of the 4 items in the list. Code:

def count(data, target_bit):
    zero_count = 0
    one_count = 0
    for numbers in data:
        if numbers[target_bit] == '0':
            zero_count += 1
        else:
            one_count += 1
    return [zero_count, one_count]

current_list = ["1001", "0001", "1111", "0011"]
oxygen_list = current_list
current_index = 1

zero_count = count(current_list, current_index)[0]
one_count = count(current_list, current_index)[1]

if zero_count > one_count:
    loop_count = 0
    for items in current_list:
        print(loop_count)
        if items[current_index] == "1":
            oxygen_list.remove(current_list[loop_count])
        loop_count += 1
        

print(current_list)

This should be rule one of modifying lists: never remove items from a list while you're iterating over that list .

Instead, you can construct a new list and omit the items that don't fit:

if zero_count > one_count:
    new_list = []
    for items in current_list:
        if items[current_index] == "0":
            new_list.append(items)
    current_list = new_list

You can do this more compactly with a list comprehension:

if zero_count > one_count:
    current_list = [items for items in current_list if items[current_index] == "0"]

PS: I noticed you call count twice, and throw away half of the results each time. Instead, you can do this:

zero_count, one_count = count(current_list, current_index)
if items[current_index] == "1":
    oxygen_list.remove(current_list[loop_count])

this right here is removing the item where the 2nd number is 1

comment out these lines and you will see it will iterate over all 4 items in the list

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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