考虑出队=[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/