【发布时间】:2020-03-15 05:28:30
【问题描述】:
我不确定我的代码是如何跳过列表中的第一项...
我尝试检查值是否与列表中的第一项相同,并尝试检查索引为零,但都跳过了第一个值。
我已经看了一段时间了。我错过了什么明显的东西吗?
使用enumerate 并检查index 的示例。
def threaded_query(self):
for ndex, query_key in enumerate(['Acct #', 'Results', 'Final Results', 'IPAccts']):
if ndex == 0:
write_to_table = pow_query_dict[query_key].format(self.login, self.value)
else:
write_to_table = pow_query_dict[query_key].format(self.login)
conn = pyodbc.connect(driver='{ODBC Driver 17 for SQL Server}', host='myserver',
database='myDB', trusted_connection='yes')
with conn:
try:
conn.autocommit = True
cursor = conn.cursor()
cursor.execute(write_to_table)
print('Committed {} data to SQL Server tables.'.format(query_key))
except BaseException as e:
print('Query failed with Exception: {}'.format(e))
检查列表中第一项的确切值的示例:
def threaded_query(self):
for query_key in ['Acct #', 'Results', 'Final Results', 'IPAccts']:
if query_key == 'Acct #':
write_to_table = pow_query_dict[query_key].format(self.login, self.value)
else:
write_to_table = pow_query_dict[query_key].format(self.login)
...
两个结果:
Committed Results data to SQL Server tables.
Committed Final Results data to SQL Server tables.
Committed IPAccts data to SQL Server tables.
正如您在结果中看到的那样,它似乎完全跳过了 if 语句中的 Acct #。
【问题讨论】:
-
最后
write_to_table = pow..行之后似乎有一个额外的缩进? -
@SeljukGülcan 是的,就是这样。我知道这是显而易见的……当您长时间盯着您的代码时,就会发生这种情况。可能应该离开然后回来。令人讨厌的是,由于某种原因,当您在 PyCharm 中工作时,它会在粘贴内容时不时更改缩进。
标签: python list loops if-statement