python - 打印循环出队的非空部分

标签 python list deque circular-list arraydeque

考虑出队=[2, 3, 4, None, None, None, 1]。它是循环的,假设 1 是出队的前面,4 是出队的后面,敲敲敲打,我们应该将这些索引存储在变量 front 和 back 下,它们的值分别是 6 和 2。

如何打印前后索引之间的值,即[1,2,3,4]。更好的是,更具体地说,我希望找到一种方法来制作一个更具体地看起来像 [1,2,3,4] 的字符串。我的代码如下,但我不认为它具有时间效率,而且,在我的代码的较大块内,我不确定这种方法是否有效。

def str(自身):

if self.size==0:       #my first thoughts are to simply catch an empty dequeue
    return "[ ]"

elif self.size==1:      #same for a dequeue of only one object.
    string = "[ "+str(self.__contents[0])+" ]"
    return string

else:
    string="[ "
    index=self.front
    while (index%self.capacity) != self.back:
        string = string + str(self.contents[index]) + ", "
        index+=1
    string=string+str(self.__contents[self.back]) + " ]"
    return string

其中 self.size=非空条目的数量,self.capacity=数组中单元格的总数,self.contents 表示数组的内容,self.front 和 self.back 表示数组的索引出队的前部和后部。

最佳答案

您想使用内置deque吗? ?如果是这样,它支持标准迭代,使列表理解非常Pythonic:

'[{}]'.format(', '.join(x for x in my_deque if x is not None)

如果它不是内置的deque,为什么不向您的类型添加迭代支持以允许上述方法(可能还有许多其他方法)。

关于python - 打印循环出队的非空部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51552365/

相关文章:

python - 在 Pygame 中正确旋转 Cannon 的问题仍然存在

python - 如何在一行中以空格分隔输入列表中的元素?

list - Prolog:搜索长度>=3的子列表

Java 迭代器双向链表

python - Pyinstaller - ImportError : No system module 'pywintypes' (pywintypes27. dll)

python - 如何使用 Django 进行有效的地理定位?

python - Keras 中的 LSTM 始终返回相同的输出

list - PhpStorm 在列表标签​​中包装多行

c++ - 为什么我更喜欢使用 vector 到双端队列

c++ - deque::push_front 不工作