解压元组的pythonic方法是什么? [英] What is the pythonic way to unpack tuples?

查看:20
本文介绍了解压元组的pythonic方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这很难看.有什么更 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]

这篇关于解压元组的pythonic方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆