![](/img/trans.png)
[英]how do i find the greatest length from a given point and make the program stop after that point with the greatest length hits the middle?
[英]How to stop appending values after length of list hits a certain limit?
我正在尝试创建一个函数,该函数允许将一个列表中最多x个项目添加到另一个列表中。 计数器将返回达到限制之前已添加到列表的项目数量(在这种情况下,限制为10)
到目前为止,我的代码是:
x = 10
def multienqueue(queue, items):
counter = 0
while len(queue) < x:
for i in items:
queue.append(i)
counter += 1
return counter
但是,我收到的输出是:
list = [4, 5, 6, 7, 8, 9, 'cow']
Trying to enqueue the list ['a', 'b', 'c', 'd', 'e']
The number added should be 3.
The number added was 5
The queue should now be: [4, 5, 6, 7, 8, 9, 'cow', 'a', 'b', 'c']
Your queue is: [4, 5, 6, 7, 8, 9, 'cow', 'a', 'b', 'c', 'd', 'e']
['a','b','c','d','e']作为items参数传递,[4、5、6、7、8、9,'cow']作为队列传递,非常感谢您对我做错的事情的帮助!
while
循环中的条件仅在到达循环体的末端并尝试重新启动时才检查。 这在您的代码中永远不会发生。 相反,您的for
循环会将items
所有值添加到queue
,并且您始终返回items
的值数量。 while
循环永远不会再运行,因为return
语句首先结束函数。
如果要保持代码的一般结构不变,则需要对其进行更改,以便在添加每个项目后执行对足够长的列表的检查。 这意味着您只需要一个循环,而不是两个互相嵌套。 您可以使其与foo
循环(与循环逻辑分开检查长度,并可能使用break
提前退出)一起使用,或者与while
循环(使用不同的逻辑找出要追加的项目)一起使用,例如queue.append(items[count])
)。
但是更好的方法可能是计算要添加到队列中的项目数。 然后,您可以使用切片从items
获取正确的数字值,并使用list.extend
将它们一次性添加到队列中。
def multienqueue(queue, items):
num = max(0, min(x - len(queue), len(items)))
queue.extend(items[:num])
return num
请注意,更Pythonic的方法可能是使用迭代器,而不是从列表中切片。 itertools.islice
可以从迭代器中获取特定数量的值。 在这种情况下,您可能不需要返回计数,因为迭代器中仍将只保留未附加的值。
如果您只想用最少的更新来修复功能,则可以尝试以下代码。 否则,Blckknght提供了一个更加Python高效的解决方案。
x = 10
def multienqueue(queue, items):
counter = 0
for i in items:
if len(queue) < x:
queue.append(i)
counter += 1
return counter
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.