Python 在给定列表中只迭代零

Python 在给定列表中只迭代零,python,loops,pseudocode,Python,Loops,Pseudocode,我有一个问题,我已经编写了伪代码,我真的很难把它翻译成可行的Python代码。它的工作原理是这样的:我列表中的0代表我可以插入数字的可用点,我想通过计算空闲空间将下一个数字插入下一个可用点,并且我为每个循环将我计数的点的数量增加1。我还试图编写此代码来处理任何给定大小的列表。我的第一次尝试是尝试索引超过列表的大小,以为它会循环回来,但它不起作用,因为您无法索引列表中不存在的点 以下是伪代码: Cycle 1: Count 1 space starting from first available

我有一个问题,我已经编写了伪代码,我真的很难把它翻译成可行的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

以下是我迄今为止设置的代码:

#大小为4的列表的输出应按以下顺序显示数字:2 1 4 3
#大小为5的列表的输出应具有以下顺序的数字:3 1 4 5 2
结果=[4,5]
打印(结果)
对于结果中的i:
myList=[0]*i
打印(myList)
计数=0
当计数

我的目标是尽可能简单地实施,尽管我觉得我错过了一些非常明显的东西,但我还是很难过。

最简单、最容易理解的方法就是使用一个索引指针,你只需要不断地重复列表,然后使用一个计数器来计算下一步需要跳过的空间量。一个简单的例子:

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)

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

def列表_循环(lst):
i=0
尽管如此:
idx=i%len(lst)
i+=1
产量idx,lst[idx]
使用
list\u cycle()

def func(大小):
l=[0]*大小
i=curr=1
对于idx,列表循环中的el(l):
如果el==0:#可用空间
如果i==0:
l[idx]=当前
i=当前值=当前值+1
如果当前>大小:
返回l
否则:#不够
i-=1
用法很简单:

print(func(4))#=>[2,1,4,3]
打印(函数(5))#=>[3,1,4,5,2]
打印(func(10))35;=>[9,1,8,5,2,4,7,6,3,10]

是否可能没有0,但您仍然需要计数?不,我们只循环,直到列表中没有0为止。
[2, 1, 4, 3]
[3, 1, 4, 5, 2]