简体   繁体   English

仅迭代给定列表 Python 中的零

[英]Iterating over only zeros in a given list Python

I have a problem that I have written pseudocode for, and I am having a really hard time translating it into workable Python code.我有一个问题,我已经为它编写了伪代码,但我很难将它翻译成可用的 Python 代码。 It works like this: the 0's in my list represent available spots that I can insert numbers into, and I want to insert the next number into the next available spot by counting the free spaces, and I increase the number of spots I count by 1 for every loop.它是这样工作的:我列表中的 0 代表我可以插入数字的可用点,我想通过计算空闲空间将下一个数字插入下一个可用点,然后我将我计算的点数增加 1对于每个循环。 I am also trying to write this code to work with list of any given size.我也在尝试编写此代码以处理任何给定大小的列表。 My first attempt was to try and index past the size of the list thinking it would loop back around but it didn't work as you cannot index a spot in your list that doesn't exist.我的第一次尝试是尝试索引超过列表的大小,认为它会循环返回,但它不起作用,因为您无法索引列表中不存在的位置。

Here is the pseudocode:这是伪代码:

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

Note: The numbers that are being inserted into the list start at 1 and increase by 1 for every loop.注意:插入列表的数字从 1 开始,每次循环增加 1。

Here is the code I have setup so far:这是我到目前为止设置的代码:

#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

My goal is to implement this as simply as possible, and I am having a hard time though I feel like I am missing something very obvious.我的目标是尽可能简单地实现这一点,虽然我觉得我错过了一些非常明显的东西,但我很难过。

Well the most straightforward and easy to comprehend way is to just work with an index pointer with which you just keep iterating the list over and over again and a counter for the amount of spaces you need to skip next.嗯,最直接和容易理解的方法是使用一个索引指针,您只需使用它一遍又一遍地迭代列表,并使用一个计数器来表示接下来需要跳过的空间量。 A quick example:一个简单的例子:

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)

Which gives as output:作为输出给出:

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

You can define generator function which will return element and it's index in source list:您可以定义生成器函数,该函数将返回元素及其在源列表中的索引:

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

Using list_cycle() we can iterate over cycled list and decrement from current counter 1 every time empty space ( 0 ) occurred and write this counter once we counted enough:使用list_cycle()我们可以迭代循环列表并在每次出现空空间( 0 ) 时从当前计数器1递减,并在我们计数足够时写入此计数器:

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

Usage is simple:用法很简单:

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]

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

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