【问题标题】:Unpacking "the rest" of the elements in list comprehension - python3to2解包列表理解中的“其余”元素 - python3to2
【发布时间】:2015-12-24 08:49:54
【问题描述】:

在 Python 3 中,我可以使用 for i, *items in tuple 将第一次从元组中分离出来,然后将其余时间隔离到项目中,例如:

>>> x = [(2, '_', 'loves', 'love', 'VBZ', 'VBZ', '_', '0', 'ROOT', '_', '_'), (1, '_', 'John', 'John', 'NNP', 'NNP', '_', '2', 'nsubj', '_', '_'), (3, '_', 'Mary', 'Mary', 'NNP', 'NNP', '_', '2', 'dobj', '_', '_'), (4, '_', '.', '.', '.', '.', '_', '2', 'punct', '_', '_')]
>>> [items for n, *items in sorted(x)]
[['_', 'John', 'John', 'NNP', 'NNP', '_', '2', 'nsubj', '_', '_'], ['_', 'loves', 'love', 'VBZ', 'VBZ', '_', '0', 'ROOT', '_', '_'], ['_', 'Mary', 'Mary', 'NNP', 'NNP', '_', '2', 'dobj', '_', '_'], ['_', '.', '.', '.', '.', '_', '2', 'punct', '_', '_']]

我需要将它反向移植到 Python 2,我不能使用 * 指针来收集元组中的其余项目。

  • Python 2 中的等价物是什么?

  • 是否仍然可以使用列表推导实现相同的目标?

  • 这个* 用法的技术名称是什么?开箱?隔离?指针?

  • 是否可以使用 __future__ 导入,以便我可以在 Python 2 中使用相同的语法?

【问题讨论】:

    标签: python list python-3.x tuples python-2.x


    【解决方案1】:

    只需使用切片跳过第一个元素:

    [all_items[1:] for all_items in sorted(x)]
    

    语法参考扩展元组解包,其中*-前缀名称称为catch-all name。见PEP 3132。语法没有反向移植。

    【讨论】:

    • 哦哦 扩展元组解包 ;P 谢谢@MartijnPieters!!
    • 简短的问题,在zip(*list_of_tuples) 的情况下,* 前缀是否会被称为其他名称,或者它也是一个包罗万象的名称?
    • @alvas:该语法实际上没有一个令人满意的名称。我也确实在这种情况下使用 catch-all ,但它现在是一个参数,所以 catch-all 参数 和双星版本 catch-all 关键字论据.
    • 这不是“参数拆包”吗?或者是别的什么?
    • @TigerhawkT3:这是调用语法的另一面。 result = some_callable(*iterable).
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-06
    • 1970-01-01
    • 2021-06-27
    • 2022-12-24
    • 2015-07-28
    • 1970-01-01
    相关资源
    最近更新 更多