解包元组的pythonic方法是什么? [英] What is the pythonic way to unpack tuples?
本文介绍了解包元组的pythonic方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这太丑了.什么是更 Pythonic 的方式来做到这一点?
导入日期时间t= (2010, 10, 2, 11, 4, 0, 2, 41, 0)dt = datetime.datetime(t[0], t[1], t[2], t[3], t[4], t[5], t[6])
解决方案
通常,您可以使用 func(*tuple)
语法.您甚至可以传递元组的一部分,这似乎是您在此处尝试执行的操作:
t = (2010, 10, 2, 11, 4, 0, 2, 41, 0)dt = datetime.datetime(*t[0:7])
这称为解包元组,也可用于其他可迭代对象(例如列表).这是另一个示例(来自 Python 教程):
<预><代码>>>>range(3, 6) # 带有单独参数的普通调用[3, 4, 5]>>>参数 = [3, 6]>>>range(*args) # 使用从列表中解压出来的参数调用[3, 4, 5]This is ugly. What's a more Pythonic way to do it?
import datetime
t= (2010, 10, 2, 11, 4, 0, 2, 41, 0)
dt = datetime.datetime(t[0], t[1], t[2], t[3], t[4], t[5], t[6])
解决方案
Generally, you can use the func(*tuple)
syntax. You can even pass a part of the tuple, which seems like what you're trying to do here:
t = (2010, 10, 2, 11, 4, 0, 2, 41, 0)
dt = datetime.datetime(*t[0:7])
This is called unpacking a tuple, and can be used for other iterables (such as lists) too. Here's another example (from the Python tutorial):
>>> range(3, 6) # normal call with separate arguments
[3, 4, 5]
>>> args = [3, 6]
>>> range(*args) # call with arguments unpacked from a list
[3, 4, 5]
这篇关于解包元组的pythonic方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文