【问题标题】:How to stop appending values after length of list hits a certain limit?列表长度达到一定限制后如何停止附加值?
【发布时间】:2018-11-18 18:44:45
【问题描述】:

我正在尝试创建一个函数,该函数允许将一个列表中最多 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'] 被传递作为队列,非常感谢您对我做错的任何帮助!

【问题讨论】:

  • 问题在于内部for 循环。在检查长度之前,它会附加 items 中的所有内容。
  • 菜鸟错误!谢谢你:)

标签: python python-3.x list loops queue


【解决方案1】:

如果您只想通过最少的更新来修复您的功能,您可以尝试下面的代码。否则 Blckknght 给出了一个更 Pythonic 和有效的解决方案。

x = 10

def multienqueue(queue, items):
    counter = 0
    for i in items:
        if len(queue) < x:
            queue.append(i)
            counter += 1
    return counter

【讨论】:

    【解决方案2】:

    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 可以从迭代器中获取特定数量的值。在这种情况下,您可能不需要返回计数,因为迭代器中仍然只有未附加的值。

    【讨论】:

    • 感谢深入、详细的回复,谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多