简体   繁体   English

在列表长度达到一定限制后如何停止附加值?

[英]How to stop appending values after length of list hits a certain limit?

I'm trying to create a function which allows a up to x amount of items from one list to be appended to another. 我正在尝试创建一个函数,该函数允许将一个列表中最多x个项目添加到另一个列表中。 The counter will return the amount of items that were appended to the list before the limit was reached (the limit being 10 in this case) 计数器将返回达到限制之前已添加到列表的项目数量(在这种情况下,限制为10)

My code as of now is: 到目前为止,我的代码是:

x = 10

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

However, the output I receive is: 但是,我收到的输出是:

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'] is passed as the items argument and [4, 5, 6, 7, 8, 9, 'cow'] is passed as the queue, any help on what I'm doing wrong is much appreciated! ['a','b','c','d','e']作为items参数传递,[4、5、6、7、8、9,'cow']作为队列传递,非常感谢您对我做错的事情的帮助!

The condition in your while loop is only checked when the end of the loop body gets reached and it tries to restart. while循环中的条件仅在到达循环体的末端并尝试重新启动时才检查。 That never happens in your code. 这在您的代码中永远不会发生。 Instead, your for loop adds all the values from items to queue , and you always return the number of values in items . 相反,您的for循环会将items所有值添加到queue ,并且您始终返回items的值数量。 The while loop never runs again, because the return statement ends the function first. while循环永远不会再运行,因为return语句首先结束函数。

If you want to keep the same general structure of your code, you need to change it so that the check for the list being long enough gets run after each item is added. 如果要保持代码的一般结构不变,则需要对其进行更改,以便在添加每个项目后执行对足够长的列表的检查。 That means you want just one loop, not two nested inside each other. 这意味着您只需要一个循环,而不是两个互相嵌套。 You can make it work with either the foo loop (checking the length separately from the looping logic, and probably using break to quit early), or the while loop (using different logic to figure out which item to append, such as queue.append(items[count]) ). 您可以使其与foo循环(与循环逻辑分开检查长度,并可能使用break提前退出)一起使用,或者与while循环(使用不同的逻辑找出要追加的项目)一起使用,例如queue.append(items[count]) )。

But a better approach might be to calculate how many items you're going to be adding to the queue up front. 但是更好的方法可能是计算要添加到队列中的项目数。 Then you can use a slice to get the right number values from items and add them to the queue in one go using list.extend . 然后,您可以使用切片从items获取正确的数字值,并使用list.extend将它们一次性添加到队列中。

def multienqueue(queue, items):
    num = max(0, min(x - len(queue), len(items)))
    queue.extend(items[:num])
    return num

Note that a more Pythonic approach would probably be to use iterators, rather than slicing from a list. 请注意,更Pythonic的方法可能是使用迭代器,而不是从列表中切片。 itertools.islice can take a specific number of values from an iterator. itertools.islice可以从迭代器中获取特定数量的值。 You might not need to return the count in that case, as the iterator would still have in it only the values left un-appended. 在这种情况下,您可能不需要返回计数,因为迭代器中仍将只保留未附加的值。

If you just want to fix your function with minimum updates you can try the code bellow. 如果您只想用最少的更新来修复功能,则可以尝试以下代码。 Otherwise Blckknght gave a more pythonic and efficient solution. 否则,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.

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