如何在python上将元组类型转换为int?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29311819/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 04:22:58  来源:igfitidea点击:

How to convert tuple type to int on python?

pythoninttuplestype-conversion

提问by Jueun Kim

I'm Python beginner. I want to convert sqlcommand result (tupletype) into inttype. How can i do that?

我是 Python 初学者。我想将 sqlcommand 结果(tuple类型)转换为int类型。我怎样才能做到这一点?

import MySQLdb

db = MySQLdb.connect("localhost","root","password","database")
cursor = db.cursor()
cursor.execute("SELECT timestamp FROM unixdb")
u_data = cursor.fetchall()

>>> print u_data
((1424794931452.0,),)

u_datatype is tupleand I want to get inttype from it.

u_datatype 是tuple,我想从中获取int类型。

采纳答案by kindall

What you have there is a tuple inside a tuple. So you want the first item of the outer tuple, which is u_data[0]: the innermost tuple. And then you want the first item of that, which is u_data[0][0]. That's a float, so to get an integer, you want to wrap the whole thing in int(), leading us to:

你所拥有的是一个元组内的元组。所以你想要外部元组的第一项,也就是u_data[0]:最里面的元组。然后你想要其中的第一项,即u_data[0][0]. 那是float,所以要得到一个整数,你想把整个东西都包装在 中int(),导致我们:

int(u_data[0][0])

回答by Eric

In case your query gives a return of more than one timestamp. You can get a list of timestamps by changing your code as follows:

如果您的查询返回一个以上的时间戳。您可以通过如下更改代码来获取时间戳列表:

...
u_data, _ = cursor.fetchall()
u_data = [int(_) for _ in udata]