仅迭代给定列表中的零 Python

Iterating over only zeros in a given list Python

我有一个问题,为此我编写了伪代码,但我很难将其转换为可用的 Python 代码。它是这样工作的:我列表中的 0 代表我可以插入数字的可用点,我想通过计算空闲空间将下一个数字插入下一个可用点,我将我计算的点数增加 1对于每个循环。我也在尝试编写此代码以处理任何给定大小的列表。我的第一次尝试是尝试索引超过列表的大小,认为它会循环回来,但它没有用,因为你无法索引列表中不存在的位置。

这是伪代码:

Cycle 1: Count 1 space starting from first available space:                         0 1 0 0 0
Cycle 2: Count 2 spaces starting from first available space from last insertion:    0 1 0 0 2
Cycle 3: Count 3 spaces starting from first available space from last insertion:    3 1 0 0 2
Cycle 4: Count 4 spaces starting from first available space from last insertion:    3 1 4 0 2
Cycle 5: Count 5 spaces starting from first available space from last insertion:    3 1 4 5 2

注意:插入列表的数字从 1 开始,每次循环增加 1。

这是我目前设置的代码:

#The output for list of size 4 should have the numbers in this order: 2 1 4 3
#The output for list of size 5 should have the numbers in this order: 3 1 4 5 2
results = [4, 5]
print(results)

for i in results:

    myList = [0] * i
    print(myList)

    count = 0

    while count < len(myList):
        
        myList[count] = count+1
        
        print(myList)
        count += 1

我的目标是尽可能简单地实现它,虽然我觉得我遗漏了一些非常明显的东西,但我很难过。

嗯,最直接、最容易理解的方法就是使用一个索引指针,您只需使用它一遍又一遍地迭代列表,以及一个计算您接下来需要跳过的空格数量的计数器。一个简单的例子:

list_sizes = [4, 5]
for list_size in list_sizes:
    your_list = [0] * list_size
    index = 0
    spaces_to_skip = 1
    space_count = 0
    while spaces_to_skip <= len(your_list):
        if your_list[index] == 0:
            # Found a space at the current pointer, determine what to do.
            if space_count == spaces_to_skip:
                # Skipped the correct amount of spaces (entries with 0)
                # Set value in the list
                your_list[index] = spaces_to_skip
                # Set the new amount of spaces to skip
                spaces_to_skip += 1
                # Reset the current space counter
                space_count = 0
            else:
                # Increase the current amount of spaces found
                space_count += 1

        # Move to next entry in list or start from the beginning
        index = (index + 1) % len(your_list)
    
    print(your_list)

输出为:

[2, 1, 4, 3]
[3, 1, 4, 5, 2]

您可以定义生成器函数,它将 return 元素及其在源列表中的索引:

def list_cycle(lst):
    i = 0
    while True:
        idx = i % len(lst)
        i += 1
        yield idx, lst[idx]

使用list_cycle()我们可以迭代循环列表并从当前计数器1递减每次空space0) 发生并在我们计数足够后写入此计数器:

def func(size):
    l = [0] * size
    i = curr = 1
    for idx, el in list_cycle(l):
        if el == 0:  # free space
            if i == 0:  # if counted enough
                l[idx] = curr
                i = curr = curr + 1
                if curr > size:
                    return l
            else:  # not enough
                i -= 1

用法很简单:

print(func(4))   # => [2, 1, 4, 3]
print(func(5))   # => [3, 1, 4, 5, 2]
print(func(10))  # => [9, 1, 8, 5, 2, 4, 7, 6, 3, 10]