簡體   English   中英

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

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM