简体   繁体   English

For 循环没有遍历列表中的所有项目

[英]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.我目前正在为编码难题(代码出现)创建 python 脚本,该难题的目标是从满足特定条件的列表中删除数字。 The problem is my for loop only iterates through 3 of the 4 items in the list.问题是我的 for 循环仅遍历列表中 4 个项目中的 3 个。 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. PS:我注意到你调用count两次,每次都扔掉一半的结果。 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这里正在删除第二个数字为 1 的项目

comment out these lines and you will see it will iterate over all 4 items in the list注释掉这些行,你会看到它将遍历列表中的所有 4 个项目

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

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