簡體   English   中英

Python function 卡在 for 循環中

[英]Python function gets stuck on a for loop

我有以下代碼:

Snapshot = {'data': []}

def SnapshotUpdater(x, side): #x is a list like [131, 18] or [135, 30]
    global Snapshot

    Rates = [x[0] for x in Snapshot['data']]

    if side == 'asks':
        for y in Snapshot['data']:
            if y[0] == x[0]:
                y[1] = x[1]
            #it still works here
            if x[0] not in Rates:
                Temp = x
                #STUCK HERE
                Snapshot['data'].append(Temp)

    print('Here')

Snapshot['data']包含以下類型的數據: [130, 12], [131, 56]...

到 function SnapshotUpdater我正在傳遞兩個元素的列表,這里是一個例子: [132, 20]

我想要做的是:function 必須檢查在Snapshot['data']內部是否有一個子列表,其中第一個元素等於我傳遞給 function 的列表的第一個元素。 所以在這種情況下,既然沒有, function 應該 append 到Snapshot['data']一個新的子列表[132, 20] 相反,如果已經存在具有相同值的元素,只需使用我傳遞給 function 的列表的第二個值更新該元素的第二個值。

問題是,由於某種原因,我的代碼卡在以下行: Snapshot['data'].append(Temp) 我不明白為什么會發生這種情況,我嘗試添加try/except語句,但沒有收到任何錯誤。 誰能幫我解決這個問題?

我懷疑您不希望for循環中的第二個if實際上在循環中。 如果side=='asksx[0] not in Rates都評估為True ,您將在每次迭代時將x附加到Snapshot['data'] ,從而增加您正在迭代的列表。 這將導致無休止的迭代。

如果您不知道您要做什么,這有幫助嗎?

Snapshot = {'data': []}

def SnapshotUpdater(x, side): #x is a list like [131, 18] or [135, 30]
    global Snapshot

    Rates = [x[0] for x in Snapshot['data']]

    if side == 'asks':
        if x[0] not in Rates:
            Temp = x
            #STUCK HERE
            Snapshot['data'].append(Temp)
        else:
            for y in Snapshot['data']:
                if y[0] == x[0]:
                    y[1] = x[1]
                #it still works here


    print('Here')

主要的是, if x[0] not in Rates計算結果為True ,則迭代Snapshot['data']並執行相同的測試是沒有意義的。 如果您可以對您的總體目標提供更多見解,也許我們可以得到更好的答案。

編輯

這是一個反映您在評論中提到的解決方案:

Snapshot = {'data': {130:8,}} # the value for 'data' is now a dict

def SnapshotUpdater(x, side): #x is a list like [131, 18] or [135, 30]
    global Snapshot

    if side == 'asks':
        Snapshot['data'][x[0]] = x[1] # If key exists, overwrites.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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