alv*_*vas 2 python tuples list python-2.x python-3.x
在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', '_', '_']]
Run Code Online (Sandbox Code Playgroud)
我需要将它反向移植到Python 2,我不能使用*指针来收集元组中的其余项目.
Python 2中的等价物是什么?
是否仍然可以使用列表理解来实现相同的目标?
这种*用法的技术名称是什么?开箱?隔离?指针?
是否有__future__可以使用的导入,以便我可以在Python 2中使用相同的语法?
只需使用切片跳过第一个元素:
[all_items[1:] for all_items in sorted(x)]
Run Code Online (Sandbox Code Playgroud)
语法称为扩展元组解包,其中*-prefixed名称称为catch-all名称.见PEP 3132.语法没有后端口.