for 循环和 if 语句交互未按预期工作?

Mik*_*SMT 0 python loops if-statement list

我不确定我的代码如何跳过列表中的第一项...

我尝试检查值是否与列表中的第一项相同,并尝试检查索引零,但都跳过第一个值。

我一直在看这个。我错过了一些明显的东西吗?

使用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))
Run Code Online (Sandbox Code Playgroud)

检查列表中第一项的确切值的示例:

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)

            ...
Run Code Online (Sandbox Code Playgroud)

两个结果:

Committed Results data to SQL Server tables.
Committed Final Results data to SQL Server tables.
Committed IPAccts data to SQL Server tables.
Run Code Online (Sandbox Code Playgroud)

正如您在结果中看到的,它似乎完全跳过Acct #了 if 语句中的 。

Sim*_*onN 5

您的with块位于else. 它应该是

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))
Run Code Online (Sandbox Code Playgroud)

  • @Mike-SMT 啊!由于在同一件事上工作太多,这种情况也经常发生在我身上。感谢上帝!我们有这样:) (2认同)