我正在嘗試創建一個包含多個這樣的字典的串列[ { token_id: 7183938r8393}, { token_id: 82838rhf88381}, ]
這就是我現在所擁有的
import pyodbc
from sqlalchemy import create_engine
import pandas as pd
import json
def all_token(x):
con = pyodbc.connect(Trusted_connection='yes', driver= '{SQL Server}',server = 'DESKTOP-
9S6405A\SQLEXPRESS' ,database ='Q42')
cursor = con.cursor()
list = []
my_dict = {}
cursor.execute("SELECT [tokens ].token_id FROM [tokens ]")
for row in cursor.fetchall():
list.append(row)
print(list)
def listToDict(list):
convert = { f"Token ID {str(i)}" : list[i][0] for i in range(0, len(list))}
return convert
all_token(list)
print(list)
dict = listToDict(list)
print(dict)
這是錯誤資訊
TypeError: object of type 'type' has no len()
uj5u.com熱心網友回復:
list = []
在這一行中,您定義了一個名為list. 這會搞砸一切,因為list是一門課。
不要使用關鍵字作為變數名
相反,將變數重命名為my_list
uj5u.com熱心網友回復:
TypeError: object of type 'type' has no len()
這里的錯誤是這list是一個保留字,不應該用作變數。更改您的變數名稱,您就可以開始了!
uj5u.com熱心網友回復:
你的縮進似乎被打破了。此外,您不應該使用關鍵字名稱來命名串列。所以我會用list1. 您發送list1到 all_token()其中沒有任何意義,因為您將list1在all_token函式中創建。所以可能你應該輸入:
return list1
代替:
print(list1)
...然后代替
all_token(list1)
寫...
list1 = all_token()
此外,您需要洗掉xall_token() 的引數。現在你有list1并且可以將它轉換成字典或任何你想要的。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/486180.html
