解压元组的pythonic方法是什么?

2022-01-19 00:00:00 python tuples

问题描述

这很难看.有什么更 Pythonic 的方式来做到这一点?

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])


解决方案

一般可以使用func(*tuple)语法.您甚至可以传递元组的一部分,这看起来就像您在这里尝试做的那样:

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])

这被称为 unpacking 元组,也可以用于其他可迭代对象(例如列表).这是另一个示例(来自 Python 教程):

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]

相关文章