[英]Python: An append() is causing an infinite loop
我有一些要修改的廣告系列,但是我必須調用服務器並導出所有廣告系列設置,以修改或添加所需的信息並將其發送回服務器。
我的修改存儲在SQLite數據庫中,因此,首先,我查詢數據庫以查找帳戶ID(我可以在不同帳戶中擁有許多廣告系列),然后按每個帳戶搜索廣告系列。
theCursor.execute('SELECT * FROM SandboxPubTB')
rows = theCursor.fetchall()
for row in rows:
accounts.append(row[7])
for account in set(accounts):
theCursor.execute('SELECT CAMPAIGNNAME, CAMPAIGNID FROM SandboxPubTB WHERE ACCOUNTID =?', (account,) )
campaignRows = theCursor.fetchall()
for campaign in campaignRows:
campId= campaign[0] + "," + campaign[1] + "," + account
campaigns.append(campId)
我的campId列表在每個條目中都包含廣告系列名稱,廣告系列ID和廣告系列帳戶ID。
之后,我遍歷列表並將值分配給廣告系列一級的變量:
for campaignNameId in set(campaigns):
campaignNameId = campaignNameId.split(',')
campaignName = campaignNameId[0]
campaignId = campaignNameId[1]
campaignAccount = campaignNameId[2]
現在是時候調用服務器來導出活動設置了:
targetUrl = "https://sites.com/api/1.0/" + campaignAccount + "/campaigns/"+ campaignId
resp = requests.get(url=targetUrl, headers=header)
r = resp.json()
temp = r['publisher_bid_modifier']['values']
如果我打印溫度,這就是我得到的:
[{
'target': 'msn-can',
'cpc_modification': 0.5
}, {
'target': 'msn-can-home',
'cpc_modification': 0.5
}, {
'target': 'smartify-journalistatecom',
'cpc_modification': 0.5
}, {
'target': 'foxnews-iosapp',
'cpc_modification': 1.22
}]
最后,這是我遇到的問題。 我想做的是遍歷上面的字典列表,如果“ target”值存在並且“ cpc_modification”與數據庫中的值不同,我將更改cpc值。 如果“目標”不存在,我想將“目標”和“ cpc_modification”附加到字典列表中。
我成功完成了第一部分,但附加部分有所不同。 在elif中,即使我使用else,temp.append也會觸發無限循環,我也不知道為什么。
for dt in r['publisher_bid_modifier']['values']:
#print(dt['target'])
#if dt['target']:
theCursor.execute('SELECT ADJUST, SITE FROM SandboxPubTB WHERE CAMPAIGNNAME =?', (campaignName,) )
campaignRows = theCursor.fetchall()
for t in campaignRows:
if t[1] == dt['target'] :
dt['cpc_modification'] = "{:.2f}".format((int(t[0]) / 100) + 1)
elif dt['target'] not in temp:
temp.append("{'target': "'" + t[1] + "'", 'cpc_modification': "'" + str(t[0]) + "'"}")
這很奇怪,因為我嘗試使用局部變量來模擬相同的行為,而且似乎可以正常工作。
data = [{
"target": "publisher1",
"cpc_modification": 1.5
},
{
"target": "publisher2",
"cpc_modification": 0.9
}
]
for t in data:
if t['target'] == "publisher10":
t['cpc_modification'] = 1.9
else:
data.append({'target': 'publisher10', 'cpc_modification': 12})
print(t['target'], t['cpc_modification'])
print(data)
我已經嘗試了很多事情,但我不知道出了什么問題。
我相信您的問題就在這里。 您正在遍歷“數據”,但同時也在將其添加到“數據”。 您應該創建一個新變量來附加。
temp = data
for t in data:
if t['target'] == "publisher10":
t['cpc_modification'] = 1.9
else:
temp.append({'target': 'publisher10', 'cpc_modification': 12})
print(t['target'], t['cpc_modification'])
print(temp)
我在這里舉了一個我正在發生的事的例子
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.