首页 > 解决方案 > 在 Python 中解压单个可迭代元素的首选方法

问题描述

鉴于我有单个元素可迭代,例如元组

t = (1,)

有没有一种将元组解包到变量中的首选方法?有很多选择,各有优劣。

unpacked, = t    #  Elegant but easy to overlook.
(unpacked,) = t  #  Maybe a bit clunky?
unpacked, *_ = t #  Creates the impression, that there might be more elements.
unpacked = t[0]  #  Same as above.
*_, unpacked = t #  Same as above, but also gives the impression
                 #  that we are accessing the last element.
[unpacked] = t   #  Elegant and obvious.

PEP8 对此有什么建议吗?

标签: python

解决方案


推荐阅读