how to convert a list value into int

大城市里の小女人 提交于 2019-12-11 19:20:03

问题


i have a pyodbc row with value (9, ) I am trying to read the value into a simple integer variable, and i find that its so hard to do so. (i am new to python so i probably miss something dumb)

doing a simple int(a_row[0]) get -

TypeError: int() argument must be a string or a number, not 'pyodbc.Row'

i try to cast the row into a list first, and its the same result

i had to force it into a integer value to work

row_id=(2, )

temp_num=0

temp_num = [number for number in row_id[0]]

temp_num=int(temp_num[0])

i just find it really bizarre that i have to do something so silly, so it must be my fault, can anyone enlighten me, where i got it wrong?


回答1:


Your solution isn't forcing it into an integer; it is creating an array of the elements (the Rows) in row_id[0], and then extracting the first one. So you could have just done a_row[0][0] initially.




回答2:


The output of fetchall of a query is a list of pyodbc.Rows:

>>> x=cursor.execute('SELECT x FROM my_tbl limit 5;').fetchall()
>>> print(x)      # list of elements of type pyodbc.Row
[(3, ), (2, ), (0, ), (5, ), (1, )]
>>> type(x[0])
pyodbc.Row

to get actual integers pulled by the query above do this

>>> [row[0] for row in x]
[3, 2, 0, 5, 1]


来源:https://stackoverflow.com/questions/25652851/how-to-convert-a-list-value-into-int

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!